BFS——迷宫最短路径

版权声明:关中大侠Lv轻侯 https://blog.csdn.net/weixin_44312186/article/details/88736331

题目概述:

        给定一个n×m的迷宫矩阵,其中*代表墙壁,不可通过;而“ ·  ”代表平地,可以通过;S代表起点,T代表终点。移动过程中,当前位置为(x,y),且每次只能向上下左右(x,y+1),(x,y-1),(x+1,y),(x-1,y)的平地移动,求S到T的最短步数。

其中迷宫矩阵如下S(2,4)  T(4,3):

                                      ` ` ` ` `

                                      ` * ` * `

                                      ` * S * `

                                      ` * * * `

                                      ` ` ` T *

代码:

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=100;

struct node
{
	int x,y;
	int step;
} S,T,NODE; //起点,终点,路径上的点

int n,m;//矩阵大小为n ×m
char martix[maxn][maxn];//迷宫矩阵
bool inq[maxn][maxn]= {false}; //判断是否进入过队列
int X[4]= {0,0,1,-1};
int Y[4]= {1,-1,0,0}; //注意x和y的对应关系

bool judge(int x,int y)     //判断[x][y]是否需要访问
{
	if(x>=n||x<0||y>=m||y<0) return false;
	if(martix[x][y]=='*') return false;
	if(inq[x][y]==true) return false;
	return true;
}

int BFS()
{
	queue<node> q;
	q.push(S);
	while(!q.empty())
	{
		node top=q.front();
		q.pop();
		if(top.x==T.x&&top.y==T.y)
		{
			return top.step;
		}
		for(int i=0; i<4; i++)
		{
			int newx=top.x+X[i];
			int newy=top.y+Y[i];
			if(judge(newx,newy))
			{
				NODE.x=newx;
				NODE.y=newy;
				NODE.step=top.step+1;
				q.push(NODE);
				inq[newx][newy]=true;
			}
		}
	}
	return -1;//无法到达终点返回-1
}

int main()
{
	scanf("%d%d",&n,&m);
	for(int x=0; x<n; x++)
	{
		getchar();//过滤掉每行后面的换行符
		for(int y=0; y<m; y++)
		{
			martix[x][y]=getchar();
		}
		martix[x][m+1]='\0';
	}
	scanf("%d%d%d%d",&S.x,&S.y,&T.x,&T.y);
	S.step=0;
	printf("%d\n",BFS());
	return 0;
}

ps:思路类似于https://blog.csdn.net/weixin_44312186/article/details/88734929

猜你喜欢

转载自blog.csdn.net/weixin_44312186/article/details/88736331