1.走出迷宫
刷题链接
https://ac.nowcoder.com/acm/problem/14572
注意1:这道题自己做的 可以通过样例但是超出时间限制
原因在于没有避免他重复回头寻找 这样一来就复杂度提升了
解决办法是通过设置已经搜索过的位置为脏位(‘#’)防止回头
复杂度降低
注意2:对于有多组输入的情况 全局变量数组一定要进行 清空
使用
#include<string.h>
memset(data, 0, sizeof(data));
flag=0;
来进行数据清理
#include<iostream>
#include<vector>
#include<algorithm>
#include<string.h>
using namespace std;
int N,M,a,b;
char data[510][510];
int flag=0;
void dfs(int x,int y){
if(x<1 || x>N || y<1 || y>M || data[x][y]=='#' ){
return;
}
if(data[x][y]=='E'){
flag=1;
return ;
}
data[x][y]='#';
dfs(x+1,y);
dfs(x,y+1);
dfs(x-1,y);
dfs(x,y-1);
return;
}
int main(){
while(cin>>N>>M){
for(int i=1;i<=N;i++){
for(int j=1;j<=M;j++){
cin>>data[i][j];
if(data[i][j]=='S'){
a=i;
b=j;
}
}
}
dfs(a,b);
if(flag==1){
cout<<"Yes"<<endl;
}