Guest User

Untitled

a guest
Jul 17th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.79 KB | None | 0 0
  1. //DFS solution
  2. //Time: O(m * n * output)
  3. //Space: O(output) for call stack
  4. class Solution {
  5. public int numIslands(char[][] grid) {
  6. int ans = 0;
  7. for(int i = 0; i < grid.length; i++) {
  8. for(int j = 0; j < grid[0].length; j++) {
  9. if(grid[i][j] == '1') {
  10. ans++;
  11. deleteIsland(grid, i, j);
  12. }
  13. }
  14. }
  15. return ans;
  16. }
  17.  
  18. private void deleteIsland(char[][] grid, int i, int j) {
  19. if(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] == '0') {
  20. return;
  21. }
  22. grid[i][j] = '0';
  23. deleteIsland(grid, i - 1, j);
  24. deleteIsland(grid, i, j - 1);
  25. deleteIsland(grid, i + 1, j);
  26. deleteIsland(grid, i, j + 1);
  27. }
  28. }
Add Comment
Please, Sign In to add comment