DFS - wyh maze

DFS - wyh maze

Title Description

Give you a n * m maze, the maze has the following logo:
S represents the starting point
t represents the end point
x represents an obstacle
on behalf of open space.
Now you want to know the Han brother can not come to the end from the beginning encounter obstacles ( can only move up and down, and can not be moved to a point has moved).

Enter a description:

A first line of input integer T (1 <= T <= 10)
Next, a T-test data set, for each set of test data, a first input line and the number n 2 m (1 <= n, m <= 500)
Next n lines of m characters representative of the maze, each character is a 4-one in the above
data to ensure that only a start and a destination

Output Description:

For each set of test data, if possible output YES, NO output if not

Examples

Entry

1
3 5
s…x
x…x
…tx

Export

YES

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
char f[1000][1000];
int x[4]={1,-1,0,0},y[4]={0,0,1,-1};
int n,m;
int dfs(int a,int b)
{
	int aa,bb,flag=0;
	if(f[a][b]=='t'){
		return 1;
	}
	else{
		for(int i=0;i<4;i++){
			aa=a+x[i];
			bb=b+y[i];
			if(f[aa][bb]!='x'&&aa>=0&&aa<n&&bb>=0&&bb<m){
				f[a][b]='x';
				flag=dfs(aa,bb);
				if(flag==1){
					return 1;
				}
				else{
					continue;
				}
			}
		}
	}
	return 0;
}
int main()
{
	int t,a,b;
	cin>>t;
	while(t--){
		cin>>n>>m;
		getchar();
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				cin>>f[i][j];
				if(f[i][j]=='s'){
					a=i;
					b=j;
				}
			}
		}
		if(dfs(a,b)){
			cout<<"YES"<<endl;
		}
		else{
			cout<<"NO"<<endl;
		}
	}
	return 0;
}
Published 98 original articles · won praise 3 · Views 4717

Guess you like

Origin blog.csdn.net/linjiayina/article/details/104101535