BFS 迷宫的最短路径问题

给点一个N*M的迷宫,再给定起点(sx,sy)和终点(gx,gy),求最短路径的长度(假设存在)。

直接BFS搜索即可。

 

 

#include<iostream>
#include<queue>
#define INF 9999999
using namespace std;
int N, M;
char maze[101][101];
typedef pair<int, int>pos;
int sx, sy, gx, gy;
int d[101][101];
//向四个方向转移时的坐标偏移数组
int dx[4] = { -1, 0, 0, 1 };
int dy[4] = { 0, -1, 1, 0 };
int BFS(){
	queue<pos> que;
	for (int i = 0; i < N; i++){
		for (int j = 0; j < M; j++){
			d[i][j] = INF;
		}
	}
	que.push(pos(sx,sy));
	//loop till the queue is empty
	while (!que.empty()){
		pos p = que.front();
		que.pop();
		if (p.first == gx&&p.second == gy){
			//end the loop while,as the road reach the end of aim
			break;
		}
		for (int i = 0; i < 4; i++){
			int nx = p.first + dx[i];
			int ny = p.second + dy[i];
			if (nx >= 0 && nx < N&&ny >= 0 && ny < M&&maze[nx][ny] != '#'&&d[nx][ny] == INF){
				que.push(pos(nx, ny));
				d[nx][ny] = d[p.first][p.second] + 1;
			}
		}
	}
	return d[gx][gy];
}
int main()
{
	while (cin >> N >> M){
		for (int i = 0; i < N; i++){
			for (int j = 0; j < M; j++){
				cin >> maze[i][j];
			}
		}
		cout << BFS() << endl;
	}
	return 0;
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值