-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAcWing2019.拖拉机(迪杰斯特拉算法).cpp
65 lines (57 loc) · 1.31 KB
/
AcWing2019.拖拉机(迪杰斯特拉算法).cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// 时间:2022.1.7 20点09分
#include<iostream>
#include<cstring>
#include<algorithm>
#include<deque>
using namespace std;
#define x first
#define y second
typedef pair<int, int> PII;
const int N=1010;
bool g[N][N],st[N][N];
int dist[N][N];
int bfs(int sx,int sy)
{
deque<PII>q;
q.push_back({sx,sy});
memset(dist,0x3f,sizeof dist);
dist[sx][sy]=0;
int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
while(q.size())
{
auto t=q.front();
q.pop_front();
if(st[t.x][t.y]) continue;//如果这个点已经被搜索过了则进行下一次循环
st[t.x][t.y]=true;
if(!t.x&&!t.y) break;
for(int i=0;i<4;i++)
{
int x=t.x+dx[i],y=t.y+dy[i];
if(x>=0&&x<N&&y>=0&&y<N)
{
int w=0;
if(g[x][y]) w=1;
if(dist[x][y]>dist[t.x][t.y]+w)
{
dist[x][y]=dist[t.x][t.y]+w;
if(!w) q.push_front({x,y});
else q.push_back({x,y});
}
}
}
}
return dist[0][0];
}
int main ()
{
int n,sx,sy;
scanf("%d%d%d",&n,&sx,&sy);
while (n -- )
{
int x,y;
scanf("%d%d",&x,&y);
g[x][y]=true;
}
printf("%d\n",bfs(sx,sy));
return 0;
}