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
| #include <bits/stdc++.h> using namespace std;
const int N = 55; int grid[N][N]; bool visSea[N][N], visLand[N][N]; int dx4[4] = {-1, 0, 1, 0}; int dy4[4] = {0, -1, 0, 1}; int dx8[8] = {-1,-1,-1,0,0,1,1,1}; int dy8[8] = {-1,0,1,-1,1,-1,0,1}; int n, m;
inline bool inside(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; }
void bfsLand(int sx, int sy) { queue<pair<int,int>> q; q.push({sx, sy}); visLand[sx][sy] = true; while (!q.empty()) { auto [x, y] = q.front(); q.pop(); for (int d = 0; d < 4; ++d) { int nx = x + dx4[d], ny = y + dy4[d]; if (inside(nx, ny) && grid[nx][ny] && !visLand[nx][ny]) { visLand[nx][ny] = true; q.push({nx, ny}); } } } }
int bfsSea(int sx, int sy) { queue<pair<int,int>> q; q.push({sx, sy}); visSea[sx][sy] = true; int islands = 0; while (!q.empty()) { auto [x, y] = q.front(); q.pop(); for (int d = 0; d < 8; ++d) { int nx = x + dx8[d], ny = y + dy8[d]; if (!inside(nx, ny)) continue; if (!grid[nx][ny] && !visSea[nx][ny]) { visSea[nx][ny] = true; q.push({nx, ny}); } else if (grid[nx][ny] && !visLand[nx][ny]) { ++islands; bfsLand(nx, ny); } } } return islands; }
int main() { ios::sync_with_stdio(false); cin.tie(nullptr);
int T; cin >> T; while (T--) { cin >> n >> m; for (int i = 0; i < n; ++i) { string s; cin >> s; for (int j = 0; j < m; ++j) grid[i][j] = s[j] - '0'; } memset(visSea, 0, sizeof(visSea)); memset(visLand, 0, sizeof(visLand));
int ans = 0; bool touched = false; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (i == 0 || i == n - 1 || j == 0 || j == m - 1) { if (!grid[i][j] && !visSea[i][j]) { touched = true; ans += bfsSea(i, j); } } } } if (!touched) ans = 1; cout << ans << '\n'; } return 0; }
|