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
| #include <iostream> #include <queue> #include <cstring> using namespace std; int t, m, n, k, sx, sy, xx, yy, cx, cy, arr[52][52], dx[4] = {0, 0, -1, 1}, dy[4] = {-1, 1, 0, 0}, ans; queue<int> qx, qy; void bfs(int x, int y) { while(!qx.empty()) { sx = qx.front(); qx.pop(); sy = qy.front(); qy.pop(); for(int i = 0; i < 4; i++) { xx = sx + dx[i]; yy = sy + dy[i]; if(xx > m || yy > n || xx < 1 || yy < 1 || !arr[yy][xx]) continue; arr[yy][xx] = 0; qx.push(xx), qy.push(yy); } } } int main() { cin >> t; while(t--) { memset(arr, 0, sizeof(arr)); ans = 0; cin >> m >> n >> k; while(k--) { cin >> cx >> cy; arr[cy + 1][cx + 1] = 1; } for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++) if(arr[i][j]) { qx.push(j), qy.push(i); bfs(j, i); ans++; } cout << ans << endl; } }
|