My dfs solution based on Q200(number of island)


  • 0
    T

    '''
    class Solution {
    int result = 0;
    int max = 0;
    public int maxAreaOfIsland(int[][] grid) {
    if( grid==null || grid.length == 0 ) return 0;

        int m = grid.length;
        int n = grid[0].length;
        
        for( int i=0; i<m; i++ ){
            for( int j=0; j<n; j++ ){
                if( grid[i][j] == 1 ){
                    max = 0;
                    dfs(grid,i,j);                    
                }
            }
        }
        return result;
    }
    
    private void dfs(int[][] grid, int i, int j ){
        
        if( i<0 || i>=grid.length || j<0 || j>=grid[0].length || grid[i][j] != 1 ) return;
        
        grid[i][j] = 0;
        max++;
        result = Math.max(max,result);
        dfs(grid,i-1,j);
        dfs(grid,i,j-1);
        dfs(grid,i,j+1);
        dfs(grid,i+1,j);
        
    }
    

    }
    '''

    The idea is simple, just record the max size of islands while doing dfs


Log in to reply
 

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