求助 BFS 70分
查看原帖
求助 BFS 70分
394729
Weight_of_the_Soul楼主2022/8/16 09:59
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;

int read() {
    int x = 0, w = 1;
    char c = getchar();

    while(c < '0' || c > '9') {
        if(c == '-')
            w = -1;

        c = getchar();
    }

    while(c >= '0' && c <= '9') {
        x = x * 10 + (c - '0');
        c = getchar();
    }

    return x * w;
}

struct Node {
    int x, y;
    int dat, f;

    Node (int x, int y, int dat, int f) : x(x), y(y), dat(dat), f(f) {}
};

queue <Node> q;

const int N = 105;

bool vis[N][N][8];
int a[N][N];
int n, m;

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

void bfs() {
    q.push(Node(1, 1, 0, -1));
    for(int i = 0; i < 8; i++)
        vis[1][1][i] = true;
    
    while(!q.empty()) {
        Node p = q.front();
        q.pop();
        int x = p.x, y = p.y, dat = p.dat, f = p.f;
        for(int i = 0; i < 8; i++) {
            int nx = x + (a[x][y] * dx[i]), ny = y + (a[x][y] * dy[i]);
            if(f != i && nx >= 1 && nx <= n && ny >= 1 && ny <= m && !vis[nx][ny][i]) {
                 vis[nx][ny][i] = true;
                 q.push(Node(nx, ny, dat + 1, i));
                 if(nx == n && ny == m) {
                    printf("%d", dat + 1);
                    return ;
                 }
            }
        }
    }

    printf("NEVER");
}

int main() {
    n = read(), m = read();
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++)
            a[i][j] = read();

    bfs();
    return 0;
}
2022/8/16 09:59
加载中...