求助BFS
查看原帖
求助BFS
219661
⚡zhangjingcan⚡楼主2020/8/30 17:12
#include <bits/stdc++.h>
using namespace std;
inline int read() {
    char c = getchar();
    int x = 0;
    bool f = 0;
    while (!isdigit(c)) f ^= !(c ^ 45), c = getchar();
    while (isdigit(c)) x = (x << 1) + (x << 3) + (c ^ 48), c = getchar();
    if (f) x = -x;
    return x;
}
const int N = 1e3 + 10;
int step[N][N];
const int dx[4] = {0, 1, 0, -1};
const int dy[4] = {1, 0, -1, 0};
struct Node {
    int x, y;
} Q[N * 2];
char a[N][N];
int n, sx, sy, ex, ey;
int bfs() {
    int head = 0, tail = 0;
    Q[tail].x = sx;
    Q[tail++].y = sy;
    memset(step, -1, sizeof(step));
    step[sx][sy] = 0;
    while (head < tail) {
        Node Tx = Q[head++];
        if (Tx.x == ex && Tx.y == ey) return step[ex][ey];
        for (int i = 0; i < 4; i++) {
            int px = Tx.x + dx[i];
            int py = Tx.y + dy[i];
            if (px < 1 || px > n || py < 1 || py > n) continue;
            if (a[px][py] == '1' || a[px][py] > -1) continue;
            step[px][py] = step[Tx.x][Tx.y] + 1;
            Q[tail].x = px, Q[tail++].y = py;
        }
    }
    return -1;
}
int main() {
    n = read();
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            cin >> a[i][j];
        }
    }
    sx = read(), sy = read();
    ex = read(), ey = read();
    printf("%d\n", bfs());
    return 0;
}

一直输出-1

2020/8/30 17:12
加载中...