题目链接:走出迷宫
DFS解法:
#include<bits/stdc++.h>
using namespace std;
const int maxn=510;
int n,m,s1,s2,t1,t2;
char mp[maxn][maxn];
int vis[maxn][maxn];
int dir[4][2]= {{1,0},{-1,0},{0,-1},{0,1}};
int flag=0;
void dfs(int x,int y) {
if(x==t1&&y==t2) flag=1;
for(int i=0; i<4; i++) {
int dx=x+dir[i][0];
int dy=y+dir[i][1];
if(!vis[dx][dy]&&mp[dx][dy]!='#'&&dx>=0&&dy>=0&&dx<n&&dy<m) {
vis[dx][dy]=1;
dfs(dx,dy);
}
}
}
int main() {
while(scanf("%d%d",&n,&m)!=EOF) {
flag=0;
memset(mp,0,sizeof(mp));
memset(vis,0,sizeof(vis));
for(int i=0; i<n; i++)
for(int j=0; j<m; j++) {
scanf(" %c",&mp[i][j]);
if(mp[i][j]=='S') {
s1=i,s2=j;
}
if(mp[i][j]=='E') {
t1=i,t2=j;
}
}
dfs(s1,s2);
if(flag) printf("Yes\n");
else printf("No\n");
}
return 0;
}
BFS解法:
#include<bits/stdc++.h>
using namespace std;
const int maxn=510;
int n,m,s,t;
int mp[maxn][maxn];
int vis[maxn][maxn];
int dir[4][2]= {{1,0},{-1,0},{0,-1},{0,1}};
queue<int > q;
int bfs(int s,int t) {
while(!q.empty()) q.pop();
q.push(s);
while(!q.empty()) {
int tmp = q.front();
q.pop();
int x=tmp/m;
int y=tmp%m;
for(int i=0; i<4; i++) {
int dx=x+dir[i][0];
int dy=y+dir[i][1];
if(dx < 0 || dy < 0 || dx >= n || dy >= m) continue;
if( mp[dx][dy] == 0) continue;
if( vis[dx][dy] != 0) continue;
if(dx*m+dy==t) return 1;
vis[dx][dy] = 1;
q.push(dx*m+dy);
}
}
return 0;
}
int main() {
while(scanf("%d%d",&n,&m)!=EOF) {
memset(mp,0,sizeof(mp));
memset(vis,0,sizeof(vis));
for(int i=0; i<n; i++)
for(int j=0; j<m; j++) {
char c;
scanf(" %c",&c);
if(c=='S') {
s=i*m+j,mp[i][j]=1;
}
if(c=='E') {
t=i*m+j,mp[i][j]=1;
}
if(c=='#') mp[i][j]=0;
if(c=='.') mp[i][j]=1;
}
if(bfs(s,t)) printf("Yes\n");
else printf("No\n");
}
return 0;
}