本道题需要注意:如果孩子的起始位置就是‘#’,那孩子就无路可走,出不来了。
所以需要特判一下,代码如下:(这是废话,不需要特判,注意题目要求)
if(ch[1][1]=='#'){printf("No\n");}
注意边界条件:
if(nx<1 || nx>n || ny<1 || ny>m){continue;}if(vis[nx][ny]==1){continue;}if(ch[nx][ny]=='#'){continue;}
dfs深度优先搜索函数如下:
void dfs(int x,int y){if(x==n && y==m){flag=true;printf("Yes\n");exit(0);}vis[x][y]=1;for(int i=0;i<4;i++){int nx=x+dx[i];int ny=y+dy[i];if(nx<1 || nx>n || ny<1 || ny>m){continue;}if(vis[nx][ny]==1){continue;}if(ch[nx][ny]=='#'){continue;}dfs(nx,ny); }
}
完整代码如下:
#include<bits/stdc++.h>
using namespace std;
const int N=105;
char ch[N][N];
int vis[N][N];
int dx[]={-1,1,0,0}; //dx,dy表示上下左右走的顺序;
int dy[]={0,0,-1,1};
bool flag=false;
int n,m;
void dfs(int x,int y){if(x==n && y==m){flag=true;printf("Yes\n");exit(0);}vis[x][y]=1;for(int i=0;i<4;i++){int nx=x+dx[i];int ny=y+dy[i];if(nx<1 || nx>n || ny<1 || ny>m){continue;}if(vis[nx][ny]==1){continue;}if(ch[nx][ny]=='#'){continue;}dfs(nx,ny); }
}
int main(){cin>>n>>m;for(int i=1;i<=n;i++){for(int j=1;j<=m;j++){cin>>ch[i][j];}}if(ch[1][1]=='#'){printf("No\n");}else{dfs(1,1);if(!flag){printf("No\n");}}return 0;
}