Straightforward DFS


  • 0
    public:
        int maxAreaOfIsland(vector<vector<int>>& grid) 
        {
            int maxArea = 0; 
            row = grid.size(), col = row? grid[0].size() : 0;
            
            for (int i = 0; i < row; ++i)
                for (int j = 0; j < col; ++j) 
                    maxArea = max(maxArea, islandArea(grid, i, j));
    
            return maxArea;
        }
        
    private:
        int islandArea(vector<vector<int>>& grid, int i, int j) 
        {
            if (i>=0 && i<row && j>=0 && j<col && grid[i][j]) {
                grid[i][j] = 0;
                return  islandArea(grid, i+1, j) +
                        islandArea(grid, i-1, j) +
                        islandArea(grid, i, j+1) +
                        islandArea(grid, i, j-1) + 1;
            }        
            return 0;
        }
        
        int row, col;
    

Log in to reply
 

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