真的看不出哪错了,求帮

P1746 离开中山路

Tiks_code @ 2024-03-17 13:08:38

#include <bits/stdc++.h>

using namespace std;

const int N = 100;

pair<int, int >st, ed;

int n;

int vis[N][N] = { 0 };

char a[N][N];

struct node {
    int x, y, cnt;
};

queue<node>q;

int dy[] = { -1,0,1,0 };
int dx[] = { 0,1,0,-1 };

int bfs(int x, int y, int cnt) {
    q.push(node{ x,y,cnt });
    vis[x][y] = 1;
    while (!q.empty()) {
        node u = q.front();
        if (ed.first == u.x && ed.second == u.y) return u.cnt;
        q.pop();
        int x = u.x, y = u.y;
        for (int i = 0; i < 4; i++) {
            int tx = x + dx[i];
            int ty = y + dy[i];
            if (tx < 0 || tx > n || ty < 0 || ty > n) continue;
            if (vis[tx][ty] || a[tx][ty] == '1') continue;

            vis[tx][ty] = 1;
            q.push(node{ tx ,ty ,cnt + 1 });
        }
    }
    return -1;
}

int main() {
    cin >> n;
    for (int i = 1; i <= n; i++) {
        scanf("%s", a[i]+1);
    }
    cin >> st.first >> st.second >> ed.first >> ed.second;
    cout << bfs(st.first, st.second, 0) << endl;
    //system("pause");
    return 0;
}

by zhangzirui66 @ 2024-03-17 13:47:16

用dist数组


by zhangzirui66 @ 2024-03-17 13:48:12

int bfs(int sx, int sy){
    q.push((node){sx, sy});
    vis[sx][sy] = 1;
    while(!q.empty()){
        x = q.front().x;
        y = q.front().y;
        q.pop();
        if(x == ta && y == tb) return dis[x][y];
        for(int i = 0; i < 4; i ++){
            tx = x + dx[i];
            ty = y + dy[i];
            if(tx <= 0 || tx > n || ty <= 0 || ty > n) continue;
            if(mp[tx][ty] == '1' || vis[tx][ty] == 1) continue;
            dis[tx][ty] = dis[x][y] + 1;
            vis[tx][ty] = 1;
            q.push((node){tx, ty});
        }
    }
    return -1;
}

by zhangzirui66 @ 2024-03-17 13:48:54

给个关注呗


by ImposterAnYu @ 2024-03-17 14:04:51

@Tiks_code 数组开小了吧


by Voltaris @ 2024-03-17 14:23:43

@Tiks_code 你对得起银狼头像吗?


by Tiks_code @ 2024-03-18 10:54:10

@Yaofangyu 激励自己的嘛


by Tiks_code @ 2024-03-18 10:55:34

@zhangzirui66 感谢感谢


|