迷宫最短路径(bfs)

#include <iostream>
#include<stdio.h>
#include<queue>
#include<string.h>
#define MAX 1000
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int n,m;
char A[MAX][MAX];
int d[MAX][MAX];//保存最近距离 
int sx,sy;//起点 
int ex,ey;//终点 
int bfs();
int main(int argc, char** argv) {
	freopen("test.txt","r",stdin);
	cin>>n>>m;
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
			d[i][j]=-1;
		}
	}
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
			char c;
			cin>>c;
			A[i][j]=c;
			if(c=='S')
			{
				sx=i;
				sy=j;
			} 
			if(c=='G')
			{
				ex=i;
				ey=j;
			}
		}
	}
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
			cout<<A[i][j]<<" ";
		}
		cout<<endl;
	}
	d[sx][sy]=0;
	cout<<bfs()<<endl;
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
			printf("%4d ",d[i][j]);
		}
		cout<<endl;
	}
	return 0; 
}
int bfs()
{
	typedef pair<int,int> p;
	int X[]={0,0,-1,1};
	int Y[]={1,-1,0,0};
	queue<p> q;
	q.push(p(sx,sy));
	while(!q.empty())
	{
		p point=q.front();
		q.pop();
			if(point.first==ex&&point.second==ey)
			{
					return d[point.first][point.second];
			}
			for(int j=0;j<=3;j++)
			{
				int a=point.first+X[j];
				int b=point.second+Y[j];
				if(a>=0&&a<n&&b>=0&&b<m)
				{
					if(A[a][b]!='#')
					{
						if(d[a][b]==-1)//未访问过 
						{
							d[a][b]=d[point.first][point.second]+1;
							q.push(p(a,b));
						}
					}
				}
			}

	}
	
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值