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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #include <bits/stdc++.h> using namespace std; char a[55][55]; int M, N, cnt; int fx[] = {1, 1, 1, 0, -1, -1, -1, 0}, fy[] = {-1, 0, 1, 1, 1, 0, -1, -1}; int fx2[] = {1, 0, -1, 0}, fy2[] = {0, 1, 0, -1}; void bfs1 () { queue<pair<int, int> > q; for (int i = 0; i <= M + 1; i ++) { for (int j = 0; j <= N + 1; j ++) { if (i == 0 || j == 0 || i == M + 1 || j == N + 1) { a[i][j] = 's'; q.emplace (i, j); } } } while (!q.empty ()) { auto [x, y] = q.front (); q.pop (); for (int i = 0; i < 8; i ++) { int X = x + fx[i], Y = y + fy[i]; if (X >= 1 && Y >= 1 && X <= M && Y <= N && a[X][Y] == '0'){ q.emplace (X, Y); a[X][Y] = 's'; } } } } void bfs3 (int x, int y) { queue<pair<int, int> > q3; q3.emplace (x, y); while (!q3.empty ()) { auto [x, y] = q3.front (); q3.pop (); for (int i = 0; i < 4; i ++) { int X = x + fx2[i], Y = y + fy2[i]; if (X >= 0 && Y >= 0 && X <= M + 1 && Y <= N + 1 && a[X][Y] == '1') { a[X][Y] = '2'; q3.emplace (X, Y); } } } } void bfs2 () { queue<pair<int, int> > q2; q2.emplace (0, 0); while (!q2.empty ()) { auto [x, y] = q2.front (); q2.pop (); for (int i = 0; i < 8; i ++) { int X = x + fx[i], Y = y + fy[i]; if (X >= 0 && Y >= 0 && X <= M + 1 && Y <= N + 1) { if (a[X][Y] == 's') { a[X][Y] = 'S'; q2.emplace (X, Y); } else if (a[X][Y] == '1') { cnt ++; a[X][Y] = '2'; bfs3 (X, Y); } } } } } void init (int M, int N) { cnt = 0; for (int i = 0; i <= M + 1; i ++) { for (int j = 0; j <= N + 1; j ++) { a[i][j] = 's'; } } } int main () { int T; cin >> T; while (T --) { cin >> M >> N; init (M, N); for (int i = 1; i <= M; i ++) { for (int j = 1; j <= N; j ++) { cin >> a[i][j]; } } bfs1 (); bfs2 (); cout << cnt << endl; } return 0; }
|