Cod sursa(job #3378249)

Utilizator TeodoRazvanStancu Teodor-Razvan TeodoRazvan Data 25 noiembrie 2026 16:56:13
Problema Car Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.81 kb
#include <bits/stdc++.h>

using namespace std;

const int inf=1e9,mod=5,di[]={0,-1,-1,0,1,1,1,0,-1},dj[]={0,0,1,1,1,0,-1,-1,-1};

struct stare {
    int dir,i,j;
};

int next_cost(int a,int b) {
    int ca=a,cb=b;
    if (a<b) swap(ca,cb);
    return min(abs(ca-cb),9-ca+cb-1);
}

int n,m,si,sj,fi,fj,a[501][501],d[10][501][501];
vector<vector<stare>>galeti;

bool ok(int i,int j) {
    if (i<1||j<1||i>n||j>m) return false;
    return true;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    freopen("car.in","r",stdin);
    freopen("car.out","w",stdout);
    cin>>n>>m>>si>>sj>>fi>>fj;
    galeti.resize(5);
    for (int i=1;i<=n;i++) {
        for (int j=1;j<=m;j++) {
            cin>>a[i][j];
            for (int k=1;k<=8;d[k++][i][j]=inf);
        }
    }
    for (int i=1;i<=8;i++) {
        d[i][si][sj]=0;
        galeti[0].push_back({i,si,sj});
    }
    int rem=8,i=0;
    while (rem>0) {
        int b=i%mod;
        for (int j=0;j<galeti[b].size();j++) {
            stare cur=galeti[b][j];
            rem--;
            if (d[cur.dir][cur.i][cur.j]!=i) continue;
            if (cur.i==fi && cur.j==fj) {
                cout<<i;
                return 0;
            }
            int ni,nj,no;
            for (int k=1;k<=8;k++) {
                ni=cur.i+di[k];
                nj=cur.j+dj[k];
                if (ok(ni,nj)) {
                    if (a[ni][nj]!=1) {
                        if (d[k][ni][nj]>i+next_cost(cur.dir,k)) {
                            d[k][ni][nj]=i+next_cost(cur.dir,k);
                            galeti[(b+next_cost(cur.dir,k))%mod].push_back({k,ni,nj});
                            rem++;
                        }
                    }
                }
            }
        }
        galeti[b].clear();
        i++;
    }
    cout<<-1;
    return 0;
}