死循环求助

B3625 迷宫寻路

klxxwyx123 @ 2024-07-05 21:59:07

#include <bits/stdc++.h>
using namespace std;
char a[105][105];
bool f=false;
int n,m;
int xx[]={1,-1,0,0},
    yy[]={0,0,1,-1};
void dfs(int x,int y){
    if(x==n&&y==m){
        f=true;
        return;
    }
    for(int i=0;i<4;i++){
        int dx=x+xx[i];
        int dy=y+yy[i];
        if(dx>=1&&dx<=n&&dy>=1&&dy<=m&&a[dx][dy]=='.'){
            dfs(dx,dy);
        }
    }
}
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            cin>>a[i][j];
        }
    }
    dfs(1,1);
    if(f) cout<<"Yes";
    else cout<<"No";
    return 0;
}

大佬求调


by haiqian @ 2024-07-05 22:36:03

@klxxwyx123

dfs里面没标记啊

会出现反复横跳的情况


by HOG_ksc @ 2024-07-06 09:09:07

dfs要把走过的路标记一次,防止走回头路


by klxxwyx123 @ 2024-07-06 09:15:51

@haiqian 谢谢,我AC了。


by klxxwyx123 @ 2024-07-06 09:18:05

@haiqian 互关一下


|