Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. #include <queue>
  2. #include <tuple>
  3. #include <cstring>
  4. #include <iostream>
  5.  
  6. using namespace std;
  7.  
  8. int mat[50][50];
  9. int group[50][50];
  10.  
  11. int dx[8] = { 1, 1, 1, 0, 0, -1, -1, -1 };
  12. int dy[8] = { 1, 0, -1, 1, -1, 1, 0, -1 };
  13.  
  14. int main(void) {
  15. ios_base::sync_with_stdio(false);
  16. cin.tie(nullptr);
  17.  
  18. while (true) {
  19. int n, m;
  20. cin >> m >> n;
  21. if (m == 0 && n == 0) break;
  22.  
  23. memset(mat, 0, sizeof(mat));
  24. memset(group, 0, sizeof(group));
  25.  
  26. for (int i = 0; i < n; i++) {
  27. for (int j = 0; j < m; j++) {
  28. cin >> mat[i][j];
  29. }
  30. }
  31.  
  32. int group_num = 0;
  33. for (int i = 0; i < n; i++) {
  34. for (int j = 0; j < m; j++) {
  35. if (mat[i][j] == 1 && group[i][j] == 0) {
  36. group[i][j] = ++group_num;
  37. queue<pair<int, int>> q;
  38. q.push(make_pair(i, j));
  39.  
  40. while (!q.empty()) {
  41. int x, y;
  42. tie(x, y) = q.front();
  43. q.pop();
  44.  
  45. for (int k = 0; k < 8; k++) {
  46. int tx = x + dx[k];
  47. int ty = y + dy[k];
  48.  
  49. if (tx < 0 || ty < 0 || tx > n - 1 || ty > m - 1 || mat[tx][ty] == 0 || group[tx][ty] != 0) continue;
  50. group[tx][ty] = group_num;
  51. q.push(make_pair(tx, ty));
  52. }
  53. }
  54. }
  55. }
  56. }
  57.  
  58. cout << group_num << '\n';
  59. }
  60.  
  61. return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement