BFS 迷宫最短路径

恩,第一次用英文写注释,,,


这个代码学的《挑战程序设计竞赛》上的(因为UVA效果太差,就不看刘汝佳了,心情好了再去看)


#include <iostream>
#include <queue>
#include <utility>
using namespace std;

#define MAX_N 100
#define MAX_M 100

int N, M;//line and cow

char maze[MAX_N][MAX_M + 1];//maze

int sx, sy;//the start point
int gx, gy;//the goal point

int d[MAX_N][MAX_M];//record the distance

//(dx, dy) is the vector that determine which direction to go
int dx[] = { 1, 0, -1, 0 }, dy[] = { 0, 1, 0, -1 };

const int INF = 100000000;//a number which is big enough
typedef pair<int, int> pr;//point

queue <pr> que;//queue ( the core data structure of BFS)

int main()
{
	cin >> N >> M;

	for (int i = 0; i < N; i++)
	{
		cin >> maze[i];
		for (int j = 0; j < M; j++)
		{
			if (maze[i][j] == 'S')
			{
				sx = i;
				sy = j;
			}
			if (maze[i][j] == 'G')
			{
				gx = i;
				gy = j;
			}
			d[i][j] = INF;//initialize distance by a big number
		}

	}

	que.push(pr(sx, sy));
	d[sx][sy] = 0;

	while (que.size())
	{
		pr p = que.front(); que.pop();

		if (p.first == gx && p.second == gy)
			break;

		for (int i = 0; i < 4; i++)
		{
		    //use vectors to go to the four directions
			int nx = p.first + dx[i], ny = p.second + dy[i];

			//if the point is fine to go
			if (0 <= nx && nx < N && 0 <= ny && ny < M && maze[nx][ny] != '#' && d[nx][ny] == INF)
			{
				que.push(pr(nx, ny));//push it into the queue
				d[nx][ny] = d[p.first][p.second] + 1;//record distance
			}
		}
	}

	cout << d[gx][gy] << endl;

	return 0;
}


这个也没说POJ上有没有这道题,我只测试了书上一组数据:
10 10
#S######.#
......#..#
.#.##.##.#
.#........
##.##.####
....#....#
.#######.#
....#.....
.####.###.
....#...G#

输出22

我觉得宽搜最重要的就是那个队列了


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值