NYOJ 58 最少步数(BFS)

                      最少步数

描述

这有一个迷宫,有0~8行和0~8列:

 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
 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

0表示道路,1表示墙。

现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?

(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)

输入
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
输出
输出最少走几步。
样例输入
2
3 1  5 7
3 1  6 7
样例输出
12
11


 1 #include<cstdio>
 2 #include<queue>
 3 #include<cstring>
 4 using namespace std;
 5 int sx,sy,ex,ey;
 6 int d[4][2]={1,0,0,1,-1,0,0,-1};
 7 bool visit[9][9];
 8 
 9 int G[9][9]=
10 {
11     1,1,1,1,1,1,1,1,1,
12     1,0,0,1,0,0,1,0,1,
13     1,0,0,1,1,0,0,0,1,
14     1,0,1,0,1,1,0,1,1,
15     1,0,0,0,0,1,0,0,1,
16     1,1,0,1,0,1,0,0,1,
17     1,1,0,1,0,1,0,0,1,
18     1,1,0,1,0,0,0,0,1,
19     1,1,1,1,1,1,1,1,1,
20 };
21 
22 struct point
23 {
24     int x;
25     int y;
26     int step;
27 };
28 
29 int bfs()
30 {
31     point init;
32     init.x=sx;
33     init.y=sy;
34     init.step=0;
35     queue<point>q;
36     q.push(init);
37     while(!q.empty())
38     {
39         point node=q.front();
40         q.pop();
41         if(node.x==ex&&node.y==ey)
42         return node.step;
43         for(int i=0;i<4;i++)
44         {
45             point newnode;
46             newnode.x=node.x+d[i][0];
47             newnode.y=node.y+d[i][1];
48             newnode.step=node.step+1;
49             if(!G[newnode.x][newnode.y]&&visit[newnode.x][newnode.y])
50             q.push(newnode);
51             visit[node.x][node.y]=false;
52         }
53     }    
54 }
55 
56 int main()
57 {
58     //freopen("in.txt","r",stdin);
59     int t;
60     scanf("%d",&t);
61     while(t--)
62     {
63         memset(visit,true,sizeof(visit));
64         scanf("%d%d%d%d",&sx,&sy,&ex,&ey);
65         int ans=bfs();
66         printf("%d
",ans);
67     }
68     return 0;
69 }               
原文地址:https://www.cnblogs.com/homura/p/4690972.html