西南民族大学第十届校赛(同步赛)B(广搜)

链接:https://ac.nowcoder.com/acm/contest/322/B
来源:牛客网
 

题目描述

X城市是一个交通十分不便利的城市,城市可以看成一个n * m大小的矩阵, 现在TRDD手里有该城市的地图:一个2*n+1行, 2 *m+1列大小的地图。现在TRDD所在的格子用S表示,机场所在的格子用T表示。 其他格子用空格表示,地图上左右相邻的两个格子如果不能通行用"|"表示, 上下相邻的两个点如果不能通行用"-"表示,”+“表示格子的四个角。 题目保证城市X最外圈无法通行(具体请看样例输入)。

为了能尽快赶到机场,TRDD想请你帮忙计算出他到达机场最少需要走过多少个格子(包括起点S和终点T)。

如果无法到达机场T,则输出"TRDD Got lost...TAT"(不包括双引号)。

输入描述:

第一行读入两个数n, m(1 <= n, m <= 3000)表示X城市的大小。

之后有2 * n + 1行, 每行有2 * m + 1个字符, 用来表示TRDD手里的地图

题目保证S和T都有且仅有一个。

输出描述:

如果TRDD能到达机场, 则输出TRDD最少需要经过几个格子
否则输出"TRDD Got lost...TAT"(不包括双引号)

示例1

输入

复制

4 3
+-+-+-+
|S| | |
+ +-+-+
| | | |
+ +-+-+
| |T  |
+ +-+ +
|     |
+-+-+-+

输出

复制

8

说明

TRDD所在的位置为(1, 1), 机场的位置为(3, 2)
路线为(1, 1) -> (2, 1) -> (3, 1) -> (4, 1) -> (4,2) -> (4,3) -> (3,3) ->(3,2)
共8个格子

示例2

输入

复制

3 3
+-+-+-+
|S|   |
+ + +-+
| | |T|
+ + +-+
|   | |
+-+-+-+

输出

复制

TRDD Got lost...TAT

说明

无法从S到达T

备注就没有写啦~~还得放图片 , 而且也没啥用。

思路:

一般的广搜板子先扔上去。这里需要注意的是,它的上下左右长度为2.

还有就是要注意一下 , 它每次都是走俩步 ,如果中间有  ’- ‘ 或 ’ | ‘挡住的话 , 其实是走不了的。

所以这里要判断一下 , 如果他走一步有没有障碍。

没啥坑点了~~

代码:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 6080;
int vis[maxn][maxn];
int n , m;
char str[maxn][maxn];
int Next[4][2] = {0,2,2,0,0,-2,-2,0}; 
struct node
{
	int x , y , step;
};
bool judge(int x , int y)
{
	if(x < 0 || y < 0 || x >= 2*n+1 || y >= 2*m+1) return false;
	if(str[x][y] != ' ')return false;
	if(vis[x][y] == true)return false;
	return true;
}
int bfs(int sx , int sy , int ex , int ey)
{
	int flag;
	queue<node> Q;
	node now;
	now.x = sx;
	now.y = sy;
	now.step = 1;
	vis[sx][sy] = true;
	Q.push(now);
	while(!Q.empty())
	{
		node next;
		now = Q.front();
		Q.pop();
		if(now.x == ex && now.y == ey)
		{
			return now.step;
		}
		for(int i = 0 ; i < 4 ; i++)
		{
			flag = 0;
			next.x = now.x + Next[i][0];
			next.y = now.y + Next[i][1];
			if(i == 0)
			{
				if(!judge(next.x , next.y-1))
				{
					flag = 1;
				}
			}
			if(i == 1)
			{
				if(!judge(next.x-1 , next.y))
				{
					flag = 1;
				}
			}if(i == 2)
			{
				if(!judge(next.x , next.y+1))
				{
					flag = 1;
				}
			}
			if(i == 3)
			{
				if(!judge(next.x+1 , next.y))
				{
					flag = 1;
				}
			}
			if(judge(next.x , next.y) && flag == 0)
			{
				next.step = now.step + 1;
				Q.push(next);
				vis[next.x][next.y] = true;
			}
		}
	}
	 return -1;
}
int main()
{	
	int sx , sy , ex , ey;
	cin >> n >> m;
	getchar();
	for(int i = 0 ; i < 2*n+1 ; i++)
	{
		gets(str[i]);
	}
	for(int i = 0 ; i < 2*n+1 ; i++)
	{
		for(int j = 0 ; j < 2*m+1 ; j++)
		{
			if(str[i][j] == 'S')
			{
				sx = i; 
				sy = j;
			}
			if(str[i][j] == 'T')
			{
				ex = i;
				ey = j;
				str[i][j] = ' ';
			}
		}
	}
int w = bfs(sx , sy , ex , ey);
if(w == -1)
{
	printf("TRDD Got lost...TAT\n");
}
else
{
	printf("%d\n" , w);
}
	
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/qq_41593380/article/details/86177223
今日推荐