DFS+BFS---(走迷宫)二维地图求最短步数
题目描述:
二维数组地图的寻路最短步数
(下标从1开始)
0 0 1 0
0 0 0 0
0 0 1 0
0 1 0 0
0 0 0 1
这样的一个4*5的矩阵,1代表路障,0可以走,从(1,1)出发,到(4,3)的位置*******答案应当为7. 一共两种走法。
- BFS 做法---BFS采用层次遍历,因此第一次遍历到终点时的层数,就是最短步数。
1 #include<bits/stdc++.h> 2 using namespace std; 3 struct Point{ 4 int x,y;//坐标 5 int step;//记录从初始点到各个点的步数 6 Point(int c,int d,int s):x(c),y(d),step(s){} 7 }; 8 const int maxn=20; 9 int start_x,start_y,end_x,end_y; 10 int m,n,cnt; 11 bool inqueue[maxn][maxn]={false}; 12 int map_[maxn][maxn]={0}; 13 int next[4][2]={0,1,0,-1,1,0,-1,0}; 14 void BFS(int x,int y){ 15 queue<Point>Q; 16 Q.push(Point(x,y,0));//压入初始点 17 inqueue[x][y]=true;//标记入过队 18 while(!Q.empty()){ 19 Point top=Q.front(); 20 Q.pop(); 21 if(top.x==end_x&&top.y==end_y){//边界 22 cnt=top.step; 23 return; 24 } 25 for(int i=0;i<4;i++){ 26 int tx=top.x+next[i][0]; 27 int ty=top.y+next[i][1]; 28 if(tx<1||ty<1||tx>m||ty>n||inqueue[tx][ty]==true||map_[tx][ty]==1) 29 continue;//剪枝 30 inqueue[tx][ty]=true; 31 Point mid=Point(tx,ty,top.step+1); 32 Q.push(mid); 33 } 34 } 35 } 36 int main(){ 37 while(cin>>m>>n){ 38 cnt=0; 39 memset(inqueue,false,sizeof(inqueue)); 40 memset(map_,false,sizeof(map_)); 41 for(int i=1;i<=m;i++){ 42 for(int j=1;j<=n;j++){ 43 cin>>map_[i][j]; 44 } 45 } 46 cin>>start_x>>start_y>>end_x>>end_y; 47 Point start=Point(start_x,start_y,0);//初始化起始点 48 BFS(start.x,start.y); 49 cout<<cnt<<endl; 50 } 51 return 0; 52 }
DFS做法
1 #include<bits/stdc++.h> 2 using namespace std; 3 int m,n,start_x,start_y,end_x,end_y,cnt,min_step=1000; 4 const int maxn=20; 5 int map_[maxn][maxn]; 6 bool visit[maxn][maxn]; 7 int next[4][2]={0,1,0,-1,1,0,-1,0}; 8 void DFS(int x,int y,int step){ 9 if(x==end_x&&y==end_y){ 10 if(step<min_step) 11 min_step=step; 12 return; 13 } 14 for(int i=0;i<4;i++){ 15 int tx=x+next[i][0]; 16 int ty=y+next[i][1]; 17 if(tx<1||ty<1||tx>m||ty>n||visit[tx][ty]==true||map_[tx][ty]==1) continue; 18 visit[tx][ty]=true; 19 DFS(tx,ty,step+1); 20 visit[tx][ty]=false; 21 } 22 } 23 int main(){ 24 while(cin>>m>>n){ 25 min_step=1000; 26 memset(visit,false,sizeof(visit)); 27 memset(map_,0,sizeof(visit)); 28 for(int i=1;i<=m;i++){ 29 for(int j=1;j<=n;j++){ 30 cin>>map_[i][j]; 31 } 32 } 33 cin>>start_x>>start_y>>end_x>>end_y; 34 visit[start_x][start_y]=true; 35 DFS(start_x,start_y,0); 36 37 cout<<min_step<<endl; 38 } 39 return 0; 40 }

浙公网安备 33010602011771号