dfs递归RE求助

P11228 [CSP-J 2024] 地图探险

Grasses_Hitler @ 2024-11-10 15:05:55

#include <bits/stdc++.h>
using namespace std;
char a[1145][1145];
int b[1145][1145];
int dx[5] = {0,1,0,-1};
int dy[5] = {1,0,-1,0};
int dfs(int idx,int x,int y,int d,int n,int m,int k,int cnt,int x0,int y0){
    if(idx > k) return cnt;
    int newx,newy;
    newx = x + dx[d];
    newy = y + dy[d];
    if(newx == x0 and newy == y0) return cnt;
    if(newx < 1 || newx > n || newy < 1 || newy > m || a[newx][newy] == 'x'){
        dfs(idx+1,x,y,(d+1)%4,n,m,k,cnt,x0,y0);
//      cout << (d+1)%4 << endl;
    }
    else{
        if(b[newx][newy]==0) cnt++;
//      cout << cnt << endl;
        b[newx][newy] = 1;
        dfs(idx+1,newx,newy,d,n,m,k,cnt,x0,y0);
//      cout << newx <<" "<< newy << endl;
    }
}
int main(){
//  freopen("explore2.in","r",stdin);
//  freopen("explore.out","w",stdout);
    int T;
    cin >> T;
    int x0,y1,d0,n,m,k,cnt=0;
    for(int i = 1;i <= T;i++){
        int n,m,k,x0,y0,d0;
        cin >> n >> m >> k >> x0 >> y1 >> d0;
        for(int j = 1;j <= n;j++){
            string tmps;
            cin >> tmps;
            for(int x = 1;x <= m;x++){
                a[j][x] = tmps[x-1];
            }
        }
        b[1][1] = 1;
        cout << dfs(0,x0,y0,d0,n,m,k,1,x0,y0) << endl;
        for(int j = 1;j <= n;j++){
            for(int x = 1;x <= m;x++){
                b[j][x] = 0;
            }
        }
    }
    return 0;
}

写得有点抽象,帮忙查查


by Mei20091011 @ 2024-11-10 15:11:12

newx和newy可能会是负数,当数组下标的时候会RE


|