NYOJ58——最小步数,简单的BFS应用

 1 #include<iostream>
2 #include<cstdio>
3 #include<cstdlib>
4 #include<cstring>
5 #include<queue>
6
7 using namespace std;
8
9 int dx[4] = {1,-1, 0, 0};
10 int dy[4] = {0, 0, 1,-1};
11 int visit[9][9];
12 int map[9][9] = {{1,1,1,1,1,1,1,1,1},{1,0,0,1,0,0,1,0,1},{1,0,0,1,1,0,0,0,1},{1,0,1,0,1,1,0,1,1},
13 {1,0,0,0,0,1,0,0,1},{1,1,0,1,0,1,0,0,1},{1,1,0,1,0,1,0,0,1},{1,1,0,1,0,0,0,0,1},{1,1,1,1,1,1,1,1,1}};
14
15 typedef struct
16 {
17 int x, y;
18 int step;
19 }Point;
20
21 int True(Point V)
22 {
23 if(V.x>=0&&V.x<=8&&V.y>=0&&V.y<=8)
24 return 1;
25 return 0;
26 }
27
28 queue<Point>q;
29 int main()
30 {
31 int i, j, ncases, flag;
32 Point Start, Target;
33
34 scanf("%d", &ncases);
35 getchar();
36 while( ncases-- )
37 {
38 scanf("%d %d %d %d",&Start.x,&Start.y,&Target.x,&Target.y);
39 getchar();
40 memset(visit, 0, sizeof(visit));
41 visit[Start.x][Start.y] = 1;
42 Start.step = 0;
43 q.push(Start);
44 while( !q.empty() )
45 {
46 Point u = q.front();
47 q.pop();
48 if(u.x==Target.x&&u.y==Target.y&&True(u))//到达目的地打印退出。
49 {
50 printf("%d\n", u.step);
51 break;
52 }
53 for(i=0; i<4; i++)
54 {
55 Point v;
56 v.x = u.x + dx[i];
57 v.y = u.y + dy[i];
58 v.step = u.step + 1;
59 if(map[v.x][v.y]!=1 && !visit[v.x][v.y] && True(v))
60 {
61 visit[v.x][v.y] = 1;
62 q.push(v);
63 }
64 }
65 }
66 while(!q.empty())
67 {
68 q.pop();
69 }
70 }
71 return 0;
72 }
73

你可能感兴趣的:(bfs)