Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- int d[4][1005][1005];
- char s[1005][1005];
- typedef pair <int, int> pii;
- int n, m;
- const int inf = 1e8;
- const int dx[] = {0, 0, 1, -1};
- const int dy[] = {1, -1, 0, 0};
- void bfs(int col) {
- queue <pii> Q;
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- if(s[i][j] == col + '0') {
- Q.push(pii(i, j));
- d[col][i][j] = 0;
- }
- }
- }
- while(!Q.empty()) {
- int x = Q.front().first;
- int y = Q.front().second;
- Q.pop();
- for(int i = 0; i < 4; i++) {
- int p = x + dx[i];
- int q = y + dy[i];
- if(0 <= p && p < n) {
- if(0 <= q && q < m) {
- if(s[p][q] != '#' && d[col][p][q] == -1) {
- d[col][p][q] = 1 + d[col][x][y];
- Q.push(pii(p, q));
- }
- }
- }
- }
- }
- }
- int dist(int c1, int c2) {
- int ans = inf;
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- if(s[i][j] == c2 + '0' && d[c1][i][j] != -1) {
- ans = min(ans, d[c1][i][j] - 1);
- }
- }
- }
- return ans;
- }
- int main (int argc, char const* argv[])
- {
- memset(d, -1, sizeof d);
- scanf("%d %d", &n, &m);
- for(int i = 0; i < n; i++) {
- scanf("%s", s[i]);
- }
- bfs(1);
- bfs(2);
- bfs(3);
- int ans = inf;
- ans = min(ans, dist(1, 2) + dist(2, 3));
- ans = min(ans, dist(1, 2) + dist(1, 3));
- ans = min(ans, dist(1, 3) + dist(2, 3));
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- if(s[i][j] == '.' && d[1][i][j] != -1 && d[2][i][j] != -1 && d[3][i][j] != -1) {
- ans = min(ans, d[1][i][j] + d[2][i][j] + d[3][i][j] - 2);
- }
- }
- }
- if(ans >= inf) ans = -1;
- printf("%d\n", ans);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement