L.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int a[500][500];
  4. int n, m;
  5. void input() {
  6. cin >> m >> n;
  7. swap(n, m);
  8. for (int i = 0; i < n; i++)for (int j = 0; j < m; j++)cin >> a[i][j];
  9. }
  10. bool ok() {
  11. for (int i = 0; i < n; i++)for (int j = 0; j < m; j++)if (a[i][j])return false;
  12. return true;
  13. }
  14. void solve() {
  15. input();
  16. int areas = 0;
  17. while (!ok()) {
  18. queue<pair<int, int>> Q;//创建一个队列
  19. ///Q.push(make_pair(0,0));//起点加入队列
  20. //a[0][0]=0;
  21. int X = 0, Y = 0;
  22. for (int i = 0; i < n; i++)
  23. for (int j = 0; j < m; j++)
  24. if (a[i][j]) {
  25. X = i;
  26. Y = j;
  27. break;//遇到1就停下
  28. }
  29. Q.push(make_pair(X, Y));
  30. a[X][Y] = 0;
  31. while (Q.size()) {
  32. pair<int, int> cur = Q.front();//获得队列的第一个元素
  33. int x = cur.first, y = cur.second;
  34. for (int dx = -1; dx <= 1; ++dx)
  35. for (int dy = -1; dy <= 1; ++dy) { //按照宽度去扩展
  36. if (abs(dx - dy) != 1)continue;
  37. int nx = x + dx, ny = y + dy;
  38. if (nx < 0 || nx > n - 1 || ny < 0 || ny > m - 1 || a[nx][ny] == 0)continue;
  39. Q.push(make_pair(nx, ny));
  40. a[nx][ny] = 0;
  41. }
  42. //cout<<cur.first<<cur.second<<endl;//计数
  43. Q.pop();//出队
  44. }
  45. ++areas;
  46. }
  47. cout << areas << endl;
  48. }
  49. int main() {
  50. //freopen("b.in.cpp","r",stdin);
  51. int t;
  52. cin >> t;
  53. while (t--) {
  54. solve();
  55. }
  56. return 0;
  57. }