#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define N 600005
#define pb push_back
#define ff first
#define ss second
#define all(x) x.begin(),x.end()
#define SZ(s) (int)s.size()
int n, w, h, vis[500][500][15], answer = INT_MAX, ans, tr;
pair <int,int> location[10];
char a[500][500];
int check(char c,int direction){
if(direction == 1 && c == 'C' || direction == 2 && c == 'A') return 4;
else if(direction == 1 && c == 'A' || direction == 2 && c == 'C') return 3;
else if(direction == 3 && c == 'C' || direction == 4 && c == 'A') return 1;
else return 2;
}
pair<pair<int,int>,pair<int,int>> f(int i,int j,int direction) {
while(direction == 1 && j < h && a[i][j + 1] != 'x') {
j++;
if(a[i][j] != '.') return {{i,1},{j,check(a[i][j],direction)}};
}
while(direction == 2 && j > 1 && a[i][j - 1] != 'x') {
j--;
if(a[i][j] != '.') return {{i,1},{j,check(a[i][j],direction)}};
}
while(direction == 3 && i > 1 && a[i - 1][j] != 'x') {
i--;
if(a[i][j] != '.') return {{i,1},{j,check(a[i][j],direction)}};
}
while(direction == 4 && i < w && a[i + 1][j] != 'x') {
i++;
if(a[i][j] != '.') return {{i,1},{j,check(a[i][j],direction)}};
}
return {{i,0},{j,direction}};
}
void solve(int i,int j,int direction,int robot,int op) {
if(vis[i][j][robot] < op) return;
vis[i][j][robot] = op;
pair<pair<int,int>,pair<int,int>> j1 = f(i,j,direction);
while(j1.ff.ss > 0) {
j1 = f(j1.ff.ff,j1.ss.ff,j1.ss.ss);
}
for(int x = 1; x <= 3; x++) {
solve(j1.ff.ff,j1.ss.ff,((j1.ss.ss+x > 4) ? (j1.ss.ss+x)%4 : j1.ss.ss+x),robot,op+1);
}
}
int main () {
cin.tie(0)->sync_with_stdio(0);
cin >> n >> h >> w;
int cp = 0;
for(int i = 1; i <= w; i++) {
for(int j = 1; j <= h; j++) {
cin >> a[i][j];
for(int k = 1; k <= n; k++){
vis[i][j][k] = INT_MAX;
}
if(a[i][j] - 48 >= 1 && a[i][j] - 48 <= 9) {
location[a[i][j] - 48] = {i,j};
a[i][j] = '.';
cp++;
}
}
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= 4; j++) {
solve(location[i].ff, location[i].ss, j, i, 0);
}
}
for(int i = 1; i <= w; i++) {
for(int j = 1; j <= h; j++) {
ans = tr = 0;
for(int k = 1; k <= n; k++) {
if(vis[i][j][k] == INT_MAX) {
tr = 1;
break;
}
ans += vis[i][j][k];
}
if(tr) continue;
answer = min(ans,answer);
}
}
cout << (answer == INT_MAX ? -1 : answer) << '\n';
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |