J.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int a[500][500];
  4. int n, m;
  5. void input() {
  6. cin >> n >> m;
  7. for (int i = 0; i < n; i++)for (int j = 0; j < m; j++)cin >> a[i][j];
  8. }
  9. bool ok() {
  10. for (int i = 0; i < n; i++)for (int j = 0; j < m; j++)if (a[i][j])return false;
  11. return true;
  12. }
  13. void solve() {
  14. input();
  15. int areas = 0, Max = 0;
  16. while (!ok()) {
  17. int cnt = 0;
  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 > n - 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. ++cnt;
  44. Q.pop();//出队
  45. }
  46. Max = max(cnt, Max);
  47. }
  48. cout << Max << endl;
  49. }
  50. int main() {
  51. //freopen("a.in","r",stdin);
  52. int t;
  53. cin >> t;
  54. while (t--) {
  55. solve();
  56. }
  57. return 0;
  58. }