fork download
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <string>
  4. #include <algorithm>
  5. #include <vector>
  6. #include <stack>
  7. #include <queue>
  8.  
  9.  
  10.  
  11. using namespace std;
  12. int dx[4] = { 1,0,-1,0 };//아래 오른쪽 위 왼쪽
  13. int dy[4] = { 0,1,0,-1 };
  14. int arr[51][51];
  15. queue<pair<int, int>>q;
  16. int bug;
  17. void BFS(int a, int b,int m, int n) {
  18. int xx, yy;
  19. q.push({a,b});
  20. while (q.size()) {
  21. int s = q.size();
  22. for (int i = 0; i < s; i++) {
  23. xx = q.front().first;
  24. yy = q.front().second;
  25. for (int i = 0; i < 4; i++) {
  26. int nx = xx + dx[i];
  27. int ny = yy + dy[i];
  28. if (0 <= nx && nx < n && 0 <= ny && ny < m && arr[nx][ny] == 1)
  29. {
  30. q.push({ nx, ny });
  31. arr[nx][ny] = 0;
  32.  
  33. }
  34. }
  35. q.pop();
  36. }
  37. }
  38. bug++;
  39. }
  40.  
  41. int main(void) {
  42. int t;
  43. cin >> t;
  44. for (int i = 0; i < t; i++) {
  45. bug = 0;
  46. int m, n, k;
  47. cin >> m >> n>>k;
  48. for (int i = 0; i < k; i++) {
  49. int x, y;
  50. cin >> x >> y;
  51. arr[y][x] = 1;
  52. }
  53.  
  54. for (int i = 0; i < n; i++) {
  55. for (int j = 0; j < m; j++) {
  56. if (arr[i][j] == 1) BFS(i, j, m, n);
  57. else continue;
  58. }
  59. }
  60. cout << bug << "\n";
  61.  
  62. }
  63. return 0;
  64. }
  65.  
Success #stdin #stdout 0s 15248KB
stdin
2
2 2 1
0 0
2 2 1
1 1
stdout
1
2