牛客--走出迷宫

题目描述

小明现在在玩一个游戏,游戏来到了教学关卡,迷宫是一个N*M的矩阵。
小明的起点在地图中用“S”来表示,终点用“E”来表示,障碍物用“#”来表示,空地用“.”来表示。
障碍物不能通过。小明如果现在在点(x,y)处,那么下一步只能走到相邻的四个格子中的某一个:(x+1,y),(x-1,y),(x,y+1),(x,y-1);
小明想要知道,现在他能否从起点走到终点。

输入描述:

本题包含多组数据。
每组数据先输入两个数字N,M
接下来N行,每行M个字符,表示地图的状态。
数据范围:
2<=N,M<=500
保证有一个起点S,同时保证有一个终点E.

输出描述:

每组数据输出一行,如果小明能够从起点走到终点,那么输出Yes,否则输出No

样例输入

3 3
S..
..E
...
3 3
S##
###
##E

样例输出

Yes
No

分析:DFS/BFS水题.

//牛客---走出迷宫    广度优先 
#include<bits/stdc++.h> 
using namespace std;

struct Node{
	int X;
	int Y;
};
int NEXT[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};//方向数组. 
int n,m,startX,startY,endX,endY;
char ch;
char arr[505][505];
int book[505][505];
void bfs(int x,int y){
	int flag = 0;
	queue<Node> Q; 
	Node node;
	node.X = x;
	node.Y = y;
	Q.push(node);
	while(!Q.empty()){
		Node node2 = Q.front();
		Q.pop();
		//cout<<node2.X<<node2.Y<<endl;
		if(node2.X==endX&&node2.Y==endY){
			cout<<"Yes"<<endl;
			flag = 1;
			break;
		} 
		for(int i = 0;i < 4;i++){
			int temX = node2.X+NEXT[i][0];
			int temY = node2.Y+NEXT[i][1];
			if(temX<=0||temX>n||temY<=0||temY>m){
				continue;
			}
			if(arr[temX][temY]=='.'&&!book[temX][temY]){
				Node node3;
				node3.X = temX;
				node3.Y = temY;
				book[temX][temY] = 1;
				Q.push(node3);
			}
		}
		
	}
	if(!flag){
		cout<<"No"<<endl;
	}
	
	
}

int main()
{
	while(cin>>n>>m){
		//初始化 
		memset(arr,'.',sizeof(arr));
		memset(book,0,sizeof(book));
		for(int i = 1;i<=n;i++){
			for(int j = 1;j<=m;j++){
				cin>>ch;
				//scanf("%c",&ch);
				if(ch=='#'){
					arr[i][j] = ch;
				}
				
				if(ch == 'S'){
					startX = i;
					startY = j;
				}
				if(ch == 'E'){
					endX = i;
					endY = j;
				}
			}
		}
		//  
		book[startX][startY] = 1;
		bfs(startX,startY);
	}
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱编程的大李子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值