Advertisement
RaFiN_

Three States cf-590C

Jul 4th, 2020
1,360
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int d[4][1005][1005];
  4. char s[1005][1005];
  5. typedef pair <int, int> pii;
  6. int n, m;
  7. const int inf = 1e8;
  8. const int dx[] = {0, 0, 1, -1};
  9. const int dy[] = {1, -1, 0, 0};
  10.  
  11. void bfs(int col) {
  12.     queue <pii> Q;
  13.     for(int i = 0; i < n; i++) {
  14.         for(int j = 0; j < m; j++) {
  15.             if(s[i][j] == col + '0') {
  16.                 Q.push(pii(i, j));
  17.                 d[col][i][j] = 0;
  18.             }
  19.         }
  20.     }
  21.    
  22.     while(!Q.empty()) {
  23.         int x = Q.front().first;
  24.         int y = Q.front().second;
  25.         Q.pop();
  26.         for(int i = 0; i < 4; i++) {
  27.             int p = x + dx[i];
  28.             int q = y + dy[i];
  29.             if(0 <= p && p < n) {
  30.                 if(0 <= q && q < m) {
  31.                     if(s[p][q] != '#' && d[col][p][q] == -1) {
  32.                         d[col][p][q] = 1 + d[col][x][y];
  33.                         Q.push(pii(p, q));
  34.                     }
  35.                 }
  36.             }
  37.         }
  38.     }
  39. }
  40.  
  41. int dist(int c1, int c2) {
  42.     int ans = inf;
  43.     for(int i = 0; i < n; i++) {
  44.         for(int j = 0; j < m; j++) {
  45.             if(s[i][j] == c2 + '0' && d[c1][i][j] != -1) {
  46.                 ans = min(ans, d[c1][i][j] - 1);
  47.             }
  48.         }
  49.     }
  50.     return ans;
  51. }
  52. int main (int argc, char const* argv[])
  53. {
  54.     memset(d, -1, sizeof d);
  55.     scanf("%d %d", &n, &m);
  56.     for(int i = 0; i < n; i++) {
  57.         scanf("%s", s[i]);
  58.     }
  59.    
  60.     bfs(1);
  61.     bfs(2);
  62.     bfs(3);
  63.  
  64.     int ans = inf;
  65.     ans = min(ans, dist(1, 2) + dist(2, 3));
  66.     ans = min(ans, dist(1, 2) + dist(1, 3));
  67.     ans = min(ans, dist(1, 3) + dist(2, 3));
  68.    
  69.     for(int i = 0; i < n; i++) {
  70.         for(int j = 0; j < m; j++) {   
  71.             if(s[i][j] == '.' && d[1][i][j] != -1 && d[2][i][j] != -1 && d[3][i][j] != -1) {
  72.                 ans = min(ans, d[1][i][j] + d[2][i][j] + d[3][i][j] - 2);
  73.             }
  74.         }
  75.     }
  76.     if(ans >= inf) ans = -1;
  77.     printf("%d\n", ans);
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement