ZZUOJ 公主与骑士 (BFS)

4316: 公主与骑士

时间限制: 1 Sec 内存限制: 128 MB

题目描述
美丽的公主被恶龙抓走了,国王召集全国各地最勇敢的骑士前往恶龙的巢穴救出公主。一个英勇的骑士冒死潜入恶龙的宫殿找到了公主殿下,现在他们想要尽快的走出宫殿,否则恶龙就会苏醒,杀死骑士。
现在交给你迷宫的地图,请告诉骑士以最短的道路需要走到出口需要走多少步。

例如上图中至少需要8步

输入
第一行一个整数n代表共有n个测试样例 (n <= 3)
每一个样例第一行两个整数r,c代表恶龙宫殿的长和宽 ( 1 <= r,c <= 200)
1 保证只包含字符“*”,“ ”,“S”,“T”四种字符。“S”代表公主和骑士所处的位置,“T”代表出口所在的位置
2 保证地图中一定存在一个起点S和一个终点T
3 保证边界处一定有墙壁

输出
输出S到T的最短距离,如果不能走出去则输出-1。

样例输入

    1 
    5 9
    *********
    * T     *
    *   *   *
    *     S *
    *********

样例输出1

6

代码:

#include <bits/stdc++.h>
using namespace std;

struct Node
{
    
    
	int x;
	int y;
	int step;
};
int walkx[4] = {
    
     0, 0, 1, -1 }, walky[4] = {
    
     1, -1, 0, 0 };
int main()
{
    
    
	int n;
	cin >> n;
	while (n--)
	{
    
    
		int r, c, result = -1;
		char mp[200][200];//mp储存是否走过,是的走到
		queue <Node>q; //Node储存走到了哪,走了多少步,和mp联系起来使用来模拟整个过程
		cin >> r >> c;
		getchar();
		for (int i = 0; i<r; i++)
		{
    
    
			for (int j = 0; j<c; j++)
			{
    
    
				mp[i][j] = getchar();
				if (mp[i][j] == 'S')
				{
    
    
					Node sta = {
    
     i, j, 0 };
					q.push(sta);
				}
			}
			getchar();
		}

		while (q.size() && result == -1)
		{
    
    
			Node node = q.front();
			q.pop();
			for (int i = 0; i<4; i++)//遍历这个位置的四个方向
			{
    
    
				int newx = node.x + walkx[i], newy = node.y + walky[i];//为了后面更好算
				if (mp[newx][newy] == 'T')//走到了
				{
    
    
					result = node.step + 1;
					break;
				}
				if (mp[newx][newy] == ' ')
				{
    
    
					Node next = {
    
     newx, newy, node.step + 1 };
					mp[newx][newy] = '*';//标记地图,不可以再走了
					q.push(next);
				}
			}
		}
		cout << result << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43700916/article/details/88364629
BFS