Cod sursa(job #3376691)

Utilizator rucimangeac ruxandra ruci Data 18 noiembrie 2026 23:09:49
Problema Car Scor 50
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.33 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("car.in");
ofstream g("car.out");

const int NMAX = 505;
const int INF = 1000000000;
const int DIRECTIONS = 8;

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

int n, m, xs, ys, xf, yf;
int a[NMAX][NMAX];
int dist[DIRECTIONS][NMAX][NMAX];
int viz[DIRECTIONS][NMAX][NMAX];

priority_queue<pair<int, pair<int, pair<int, int>>>> q;

bool check(int i, int j) {
    return (i >= 1 && i <= n && j >= 1 && j <= m);
}

void dijkstra() {
    for (int d = 0; d < DIRECTIONS; d++) {
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                dist[d][i][j] = INF;
            }
        }
    }

    for (int d = 0; d < DIRECTIONS; d++) {
        dist[d][xs][ys] = 0;
        q.push({0, {d, {xs, ys}}});
    }

    while (!q.empty()) {
        int cost_curent = -q.top().first;
        int dir_curenta = q.top().second.first;
        int x = q.top().second.second.first;
        int y = q.top().second.second.second;
        q.pop();
        if (viz[dir_curenta][x][y] == 0) {
            viz[dir_curenta][x][y] = 1;

            if (x == xf && y == yf) {
                return;
            }
            for (int k = -2; k <= 2; k++) {
                int ndirection = (dir_curenta + k + 8) % DIRECTIONS;
                int nx = x + dx[ndirection];
                int ny = y + dy[ndirection];
                int cost_mutare = abs(k);

                if (check(nx, ny) && a[nx][ny] == 0) {
                    if (dist[dir_curenta][x][y] + cost_mutare < dist[ndirection][nx][ny]) {
                        dist[ndirection][nx][ny] = dist[dir_curenta][x][y] + cost_mutare;
                        q.push({-dist[ndirection][nx][ny], {ndirection, {nx, ny}}});
                    }
                }
            }
        }
    }
}

int main() {
    f >> n >> m >> xs >> ys >> xf >> yf;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            f >> a[i][j];
        }
    }

    dijkstra();

    int ans = INF;
    for (int d = 0; d < DIRECTIONS; d++)
    {
        if (dist[d][xf][yf] < ans)
            ans = dist[d][xf][yf];
    }

    if (ans == INF) {
        g << -1;
    } else {
        g << ans;
    }

    return 0;
}