fork(1) download
  1. #include<cstdio>
  2. #include<iostream>
  3. using namespace std;
  4. int a[100][100];
  5. int d[100][100];
  6. int dx[8] = { 0,0,-1,1,-1,1,1,-1 };
  7. int dy[8] = { -1,1,0,0,-1,1,-1,1 };
  8. void dfs(int x, int y) {
  9. d[x][y] = 1;
  10. for (int k = 0; k < 8; k++) {
  11. int nx = x + dx[k];
  12. int ny = y + dy[k];
  13.  
  14. if (nx >= 0 && nx < 50 && ny >= 0 && ny < 50) {
  15. if (d[nx][ny] == 0 && a[nx][ny] == 1) {
  16. dfs(nx, ny);
  17. }
  18. }
  19. }
  20.  
  21. }
  22. int main() {
  23. while (1) {
  24. int w = 0;
  25. int h = 0;
  26. cin >> w >> h;
  27. if (w == 0 && h == 0) {
  28. break;
  29. }
  30.  
  31. for (int i = 0; i < h; i++) {
  32. for (int j = 0; j < w; j++) {
  33. cin >> a[i][j];
  34. }
  35. }
  36. int cnt = 0;
  37. for (int i = 0; i < h; i++) {
  38. for (int j = 0; j < w; j++) {
  39. if (d[i][j] == 0 && a[i][j] == 1) {
  40. dfs(i,j);
  41. cnt = cnt +1;
  42. }
  43. }
  44. }
  45. cout << cnt << endl;
  46.  
  47. }
  48. return 0;
  49. }
Success #stdin #stdout 0s 15312KB
stdin
1 1
0
2 2
0 1
1 0
3 2
1 1 1
1 1 1
5 4
1 0 1 0 0
1 0 0 0 0
1 0 1 0 1
1 0 0 1 0
5 4
1 1 1 0 1
1 0 1 0 1
1 0 1 0 1
1 0 1 1 1
5 5
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
0 0
stdout
0
1
1
2
3
3