1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| #include <iostream> #include <cstring> #include <queue> #include <algorithm> using namespace std; int map[100][100]; bool visited[100][100]; int N, ans =1e9; int dx[4] = { -1, 1, 0, 0 }; int dy[4] = { 0, 0, -1, 1 }; void DFS(int x, int y, int idx) { visited[x][y] = true; map[x][y] = idx; for (int dir = 0; dir < 4; ++dir) { int d_x = x + dx[dir]; int d_y = y + dy[dir]; if (d_x > -1 && d_y > -1 && d_x < N && d_y < N) { if (map[d_x][d_y] == 0 || visited[d_x][d_y]) continue; DFS(d_x, d_y, idx); } } } int BFS(int x, int y) { memset(visited, false, sizeof(visited)); queue<pair<int, int>> q; q.push({ x, y }); int temp = map[x][y]; int res = 0; while (int len = q.size()) { while(len--) { int x = q.front().first; int y = q.front().second; q.pop(); for (int dir = 0; dir < 4; ++dir) { int d_x = x + dx[dir]; int d_y = y + dy[dir]; if (d_x > -1 && d_y > -1 && d_x < N && d_y < N) { if (map[d_x][d_y] != 0 && map[d_x][d_y] != temp) return res; if (map[d_x][d_y] == 0 && !visited[d_x][d_y]) { visited[d_x][d_y] = true; q.push({ d_x, d_y }); } } } } res++; } return ans; } int main() { cin >> N; int idx = 1; for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { cin >> map[i][j]; } } for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { if (visited[i][j] || map[i][j] == 0) continue; DFS(i, j, idx++); } } for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { if (map[i][j] == 0) continue; ans = min(ans, BFS(i, j)); } } cout << ans << "\n"; return 0; }
|