gelita

Leetcode 200 num of islands java

Apr 19th, 2020
1,293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.54 KB | None | 0 0
  1. // package whatever; // don't place package name!
  2.  
  3. import java.io.*;
  4.  
  5. // Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
  6.  
  7. // Example 1:
  8.  
  9. // Input:
  10. // 11110
  11. // 11010
  12. // 11000
  13. // 00000
  14.  
  15. // Output: 1
  16. // Example 2:
  17.  
  18. // Input:
  19. // 11000
  20. // 11000
  21. // 00100
  22. // 00011
  23.  
  24. // Output: 3
  25.  
  26. class Solution {
  27.     public int numIslands(char[][] grid) {
  28.         //if grid is empty or null return 0 islands
  29.         if(grid == null || grid.length == 0){
  30.           return 0;
  31.         }
  32.         int islandCount = 0;
  33.         for(int i = 0; i<grid.length; i++){ //number of rows = grid length
  34.           for(int j = 0; j <grid[i].length; j++){ //number of cols = grid[i].length
  35.             if(grid[i][j] == '1'){
  36.               islandCount += dfs(grid, i, j);
  37.             }
  38.           }        
  39.         }
  40.         return islandCount;
  41.     }
  42.     private int dfs(char[][] grid, int i, int j){
  43.       // if i or j is out of bounds or if char == "0" --> do nothing
  44.       if(i < 0 || i >= grid.length || j >= grid[i].length || j <0 || grid[i][j] == '0'){
  45.         return 0;
  46.       }
  47.       grid[i][j] = '0'; //change the visited "1" char to a "0"
  48.       //if a "1" is found in that space then recursively do  a search of it's neighbors
  49.       dfs(grid, i-1, j);
  50.       dfs(grid, i+1, j);
  51.       dfs(grid, i, j-1);
  52.       dfs(grid, i, j+1);
  53.       return 1;
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment