5ms java using dfs & cache


  • 0
    S
    public class Solution {
    public int numIslands(char[][] grid) { 
        if(grid.length == 0) return 0; 
        
        boolean[][] visited = new boolean[grid.length][grid[0].length]; 
        int countIsland = 0; 
        for(int row=0; row<grid.length; row++) { 
            for(int col=0; col<grid[0].length; col++) { 
                if(grid[row][col] == '1' && !visited[row][col]) { 
                    markLand(grid, visited, row, col);
                    countIsland++;         
                }
            }
        }
        return countIsland; 
    }
        
    private void markLand(char[][] grid, boolean[][] visited, int row, int col) { 
        if(row < 0 || row >= grid.length) return; 
        if(col < 0 || col >= grid[0].length) return; 
        if(grid[row][col] == '0' || visited[row][col]) return; 
        
        visited[row][col] = true; 
        
        markLand(grid, visited, row-1, col);
        markLand(grid, visited, row+1, col);
        markLand(grid, visited, row, col-1);
        markLand(grid, visited, row, col+1);
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.