zengzeyu @ 2024-10-18 21:26:50
rt
陷入无限递归
#include<bits/stdc++.h>
using namespace std;
char c[105][105];
int n,m;
bool dfs(int x,int y){
if(c[x][y] == '#'){
return false;
}
if(x == n && y == m){
return true;
}
if(x < 1 || y < 1 || x > n || y > m){
return false;
}
bool u = dfs(x-1,y),l = dfs(x,y-1),r = dfs(x,y+1),d = dfs(x+1,y);
bool res = u || l || r || d;
return res;
}
int main(){
cin>>n>>m;
for(int i = 1;i <= n;i ++){
for(int j = 1;j <= m;j ++){
cin>>c[i][j];
}
}
bool tmpv = dfs(1,1);
tmpv?cout<<"Yes":cout<<"No";
}
by kczw @ 2024-10-18 21:33:14
@zengzeyu 不难发现你的代码会在几个点来回走
by kczw @ 2024-10-18 21:35:07
@zengzeyu 你可以使用一个数组记录某个点是否被遍历过,如果已经被遍历过了,那么没有必要继续dfs,而是应该返回退出单次dfs并且返回假。
by zengzeyu @ 2024-10-18 21:37:20
@kczw 感谢大佬!
by kczw @ 2024-10-18 21:38:24
@zengzeyu AC 代码
#include<bits/stdc++.h>
using namespace std;
char c[105][105];
int n,m,vis[105][105];
bool dfs(int x,int y){
if(c[x][y] == '#'||vis[x][y]==1//如果已经被遍历,没有必要二次遍历
){
return false;
}
if(x == n && y == m){
return true;
}
if(x < 1 || y < 1 || x > n || y > m){
return false;
}
vis[x][y]=1;//标记为已被遍历
bool u = dfs(x-1,y),l = dfs(x,y-1),r = dfs(x,y+1),d = dfs(x+1,y);
bool res = u || l || r || d;
return res;
}
int main(){
cin>>n>>m;
for(int i = 1;i <= n;i ++){
for(int j = 1;j <= m;j ++){
cin>>c[i][j];
}
}
bool tmpv = dfs(1,1);
tmpv?cout<<"Yes":cout<<"No";
}
by zengzeyu @ 2024-10-18 21:49:59
AC了,本贴结(顺便 %@kczw 大佬)
by zengzeyu @ 2024-10-28 17:56:02
已关