迷宫最短路径dfs和bfs代码分析

dfs用递归一步步试探,在所有路径中选出最短的一条路径

代码:

//0是路,1是墙 
#include<iostream>
#include<algorithm>
using namespace std;
int x1,y1,x2,y2;//起点坐标终点坐标
int c=999999; //步数 
int dir[4][2]={-1,0,1,0,0,-1,0,1};
int mg[5][5]={0,0,1,1,1,
              0,0,1,1,1,
              0,1,0,1,1,
              1,0,1,1,1,
              0,0,0,0,0
			 };
void dfs(int x,int y,int t)
{
	int i,xx,yy;
	if (x==x2&&y==y2)//到达终点 
	{
		c=min(c,t);//取最小值 
		return ;
	}
	mg[x][y]=1;//将走过的路设1,以免下次又以为这是一条路,又走回来 
	for (i=0;i<4;i++)
	{
		xx=x+dir[i][0];
		yy=y+dir[i][1];//生成新的方向坐标 
		if (xx<0||xx>=5||yy<0||yy>=5||mg[xx][yy]==1)//超出地图,或者为墙,则要重新换个方向走 
		 continue;
		dfs(xx,yy,t+1);//步数+1,以xx,yy为新的坐标,来进行对下次的方向进行选择又生成新的xxyy 
		mg[xx][yy]=0;//这一步是当走到终点了,或者是有一个xxyy坐标上下左右都不能走,则要将刚走过的路(之前设为墙了)恢复成路 
	}
}
int main()
{
	cin>>x1>>y1>>x2>>y2;
	dfs(x1,y1,0);
	cout<<c;
	return 0;
}

bfs用队列一层一层的走,每次只取最短的

代码:

#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
struct st
{
   int x,y,c=0;//行列坐标xy,c为步数	
};
queue<struct st> xz;//创建一个队列xy 
int dir[4][2]={-1,0,1,0,0,-1,0,1};
int mg[5][5]={0,0,1,1,1,
              0,0,0,1,1,
              0,1,0,1,1,
              0,0,0,1,1,
              0,0,0,0,0
			 };
int bfs(struct st s,struct st e)
{
	struct st t;
	int i;
	xz.push(s);//先将起点坐标的信息入队 
	mg[s.x][s.y]=1;
	while (!xz.empty())//队列为空,说明到达终点,完毕 
	{
		s=xz.front(); //获取队头元素 
		xz.pop();//删除后队列为空 
		if (s.x==e.x&&s.y==e.y)//到达终点,返回步数c 
		  return s.c;
		for (i=0;i<4;i++)
		{
			t.x=s.x+dir[i][0];
			t.y=s.y+dir[i][1];
			if (t.x<0||t.x>=5||t.y<0||t.y>=5||mg[t.x][t.y])//不能走 
			 continue;
			 t.c=s.c+1;  //步数加1 
			 mg[t.x][t.y]=1;//走过的路赋1 
			 xz.push(t);// 将新的坐标和步数信息t入队 
		}
	}
}
int main()
{
	struct st s,e;
	cin>>s.x>>s.y>>e.x>>e.y;
	cout<<bfs(s,e)<<endl;
	return 0;
}

打印出路径

//输入0为路,1为墙,5*5地图 
//从左上角 走到 右下角 
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
int mg[5][5];
int dir[4][2]={-1,0,1,0,0,-1,0,1};
struct node
{
	int x,y,c;
}jl[5][5];//记录路径 
int bfs()
{
	int i;
	queue<struct node> Q;
	struct node s;
	struct node t;
	s.x=s.y=s.c=0;
	mg[s.x][s.y]=1;
	Q.push(s);
	while (!Q.empty())
	{
		s=Q.front();
		Q.pop();
		if(s.x==4&&s.y==4)//达到终点 
		{
			return s.c;
		}
		for (i=0;i<4;i++)
		{
			t.x=s.x+dir[i][0];
			t.y=s.y+dir[i][1];
			if (t.x>=0&&t.x<5&&t.y>=0&&t.y<5&&mg[t.x][t.y]==0)
			{
				t.c=s.c+1;
				jl[t.x][t.y].x=s.x;//这里的jl是记录路径 
				jl[t.x][t.y].y=s.y;
				mg[t.x][t.y]=1;
				Q.push(t);
			}
		}
	}
	return 0;
}
void print(int xx,int yy)//递归打印路径  
{
	if (xx==0&&yy==0)
	 {
	 	cout<<xx<<" "<<yy<<endl;
	 	return ;
	 }
	 print(jl[xx][yy].x,jl[xx][yy].y);
	 cout<<xx<<" "<<yy<<endl;
}
int main()
{
	int i,j;
	for (i=0;i<5;i++)
	for (j=0;j<5;j++)
	 cin>>mg[i][j];
	cout<<bfs()<<endl;
	print(4,4);
}

    原文作者:BFS
    原文地址: https://blog.csdn.net/qq_36238595/article/details/54945270
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞