bfs-迷宫

给出一张地图,这张地图被分为n×m(n,m<=100)个方块,任何一个方块不是平地就是高山。平地可以通过,高山则不能。现在你处在地图的(x1,y1)这块平地,问:你至少需要走几个空地才能到达目的地(x2,y2)?你只能沿着水平和垂直方向的平地上行进。,还可以自行打印路径

在这里插入图片描述
Input
第1行:n m
第2至n+1行:整个地图地形描述(0:空地;1:高山),
如(图)第2行地形描述为:1 0 0 0 0 1 0
第3行地形描述为:0 0 1 0 1 0 0
……
第n+2行:x1 y1 x2 y2 (分别为起点、终点坐标)
Output
s (即最少的行走次数)
Sample Input
5 7
1 0 0 0 0 1 0
0 0 1 0 1 0 0
0 0 0 0 1 0 1
0 1 1 0 0 0 0
0 0 0 0 1 1 0
1 3 1 7
Sample Output

10
————————————————
版权声明:本文为CSDN博主「_Alexander」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44091178/article/details/88767367

 1  1 #include<iostream>
 2  2 #include<queue> 
 3  3 using namespace std;
 4  4 struct node
 5  5 {//状态 
 6  6     int x,y;
 7  7     int step;//当前状态的步数 
 8  8 };
 9  9 int dir[]={0,1,0,-1,0};//方向 
10 10 //int par[1001]={0};//加入路径搜索,适用于带有状态迭代的路径搜索中,因为父亲只有一个,,,bfs形成的是一颗搜索树
11 11 void print(int index)
12 12 {
13 13     if(par[index]==0)
14 14     {
15 15         cout<<index<<" "; return ;
16 16     }
17 17     else
18 18     {
19 19         int parent_index=par[index];
20 20         print(parent_index);
21 21         cout<<index<<" ";
22 22     }
23 23 }
24 24 int main()
25 25 {
26 26     int n,m,x1,x2,y1,y2;
27 27     int map[100][100];
28 28     cin>>n>>m;
29 29     int *visit=new int[n*m+3];//判重 
30 30     for(int i=0;i<n*m+3;i++) visit[i]=0;
31 31     for(int i=1;i<=n;i++)
32 32     {//初始化 
33 33         for(int j=1;j<=m;j++)
34 34         {
35 35             cin>>map[i][j];
36 36         }
37 37     }
38 38     cin>>x1>>y1>>x2>>y2;
39 39     node start;//初始状态 
40 40     start.x=x1; start.y=y1; start.step=0;
41 41     queue<node> q;
42 42     visit[(x1-1)*m+y1]=true;
43 43     q.push(start);
44 44     if(start.x==x2&&start.y==y2)
45 45     {//防止刁钻数据 
46 46         cout<<"step"<<":"<<0<<endl;
47 47         return 0;
48 48     }
49 49     while(!q.empty())
50 50     {//bfs 
51 51         node local=q.front();
52 52         q.pop();
53 53         for(int i=0;i<4;i++)
54 54         {//注意,这里指的x,y是指结点的行,列,而非坐标,,,,不要混淆 
55 55             int x=local.x+dir[i],y=local.y+dir[i+1];
56 56             if(x<1||x>n||y<1||y>m||visit[(x-1)*m+y]||map[x][y]) continue;
57 57             node temp=local;
58 58             temp.x=x; temp.y=y; temp.step++;
59 59             
60 60             visit[(x-1)*m+y]=1;
61 61             //par[(x-1)*m+y]=m*(local.x-1)+local.y;
62 62             q.push(temp);
63 63             if(temp.x==x2&&temp.y==y2)
64 64             {
65 65                 cout<<"step"<<":"<<temp.step<<endl;
66 66                 //cout<<"打印路径:"<<endl;
67 67                 //int end=(x2-1)*m+y2;
68 68                 //print(end);
69 69                 
70 70                 delete visit;
71 71                 return 0;
72 72             }
73 73         }
74 74     }    
75 75     delete visit;
76 76     cout<<"no"<<endl;
77 77     return 0;
78 78  } 

//以上也实现了路径打印操作,详情可见注释掉的部分代码!

猜你喜欢

转载自www.cnblogs.com/zww-kjj/p/12237131.html