简单的迷宫问题

链接:
https://www.nowcoder.com/acm/contest/93/D
来源:牛客网

题目描述

给你一个n*m的迷宫,这个迷宫中有以下几个标识:

s代表起点

t代表终点

x代表障碍物

.代表空地

现在你们涵哥想知道能不能从起点走到终点不碰到障碍物(只能上下左右进行移动,并且不能移动到已经移动过的点)。

输入描述:

输入第一行一个整数T(1<=T<=10)
接下来有T组测试数据,对于每一组测试数据,第一行输入2个数n和m(1<=n,m<=500)
接下来n行,每行m个字符代表这个迷宫,每个字符都是上面4个中的一种
数据保证只有一个起点和终点

输入

1
3 5
s...x
x...x
...tx

输出

YES

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
char st1[505][505];//定义字符数组 
int  st2[505][505];//定义访问数组,未访问时全都为0 
int s1[4]={0,1,0,-1};//定义常量数组 
int s2[4]={1,0,-1,0};//方向为 上 下 左 右四个方向 
int n,m,ans;
void bianli(int x,int y)
{
	st2[x][y]=1;//访问过的位置全都为1 
	if(st1[x][y]=='t')
	{
		ans=1;
		return ;
	}
	else
	for(int i=0;i<4;i++)//遍历上,下,左,右,四个方向, 
	{
		int x1=x+s1[i]; 
		int y1=y+s2[i];
		if(x1>=0 && x1<=n && y1>=0 &&y1<=m && st2[x1][y1]!=1 && st1[x1][y1]!='x' )//判断边界条件,判断避免重复,递归循环。 
		bianli(x1,y1);
	}
}
int main()
{
	int a,b,c,d,t1,k,t2,t3,t4,t5,t6,t7,sum=0.0;
	char ch1,ch2,ch;
	cin>>k;
	while(k--)
	{
		ans=0;
		memset(st2,0,sizeof(st2));
		cin>>n>>m;
		for(int i=0;i<n;i++)
			for(int j=0;j<m;j++)
			{
				cin>>st1[i][j];
				if(st1[i][j]=='s')
				{	
					a=i;
					b=j;
				}		
			}
		bianli(a,b);
		if(ans==1)
		{
			cout<<"YES"<<endl;
		}
		else
		{
			cout<<"NO"<<endl;
		}
		
	}
}		


输出描述:

对于每一组测试数据,如果可以的话输出YES,不可以的话输出NO
    原文作者:迷宫问题
    原文地址: https://blog.csdn.net/guozuofeng/article/details/79827528
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞