fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void dfs(int arr[][10], int row, int col, bool visited[][10])
  5. {
  6. visited[row][col] = true;
  7.  
  8. int rowMoves[] = {-1, 1, 0, 0};
  9. int colMoves[] = {0, 0, -1, 1};
  10.  
  11. for (int i = 0; i < 4; i++)
  12. {
  13. int newRow = row + rowMoves[i];
  14. int newCol = col + colMoves[i];
  15.  
  16. if (newRow >= 0 && newRow < 10 && newCol >= 0 && newCol < 10 && arr[newRow][newCol] == 1 && !visited[newRow][newCol])
  17. {
  18. dfs(arr, newRow, newCol, visited);
  19. }
  20. }
  21. }
  22.  
  23. int count(int arr[][10])
  24. {
  25. int count = 0;
  26. bool visited[10][10] = {
  27. false
  28. };
  29.  
  30. for (int i = 0; i < 10; i++)
  31. {
  32. for (int j = 0; j < 10; j++)
  33. {
  34. if (arr[i][j] == 1 && !visited[i][j])
  35. {
  36. dfs(arr, i, j, visited);
  37. count++;
  38. }
  39. }
  40. }
  41.  
  42. return count;
  43. }
  44.  
  45. int main()
  46. {
  47. int arr[10][10];
  48.  
  49. for (int i = 0; i < 10; i++)
  50. {
  51. for (int j = 0; j < 10; j++)
  52. {
  53. cin >> arr[i][j];
  54. }
  55. }
  56.  
  57. int island = count(arr);
  58. cout << island << endl;
  59.  
  60. return 0;
  61. }
Success #stdin #stdout 0.01s 5424KB
stdin
1 1 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 1 1 0
0 0 0 0 1 1 1 1 0 0
0 0 0 0 0 1 1 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 1 1
stdout
3