天天看點

LeetCode-Max Area of Island

Description:

Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

Example 1:

[[0,0,1,0,0,0,0,1,0,0,0,0,0], 
 [0,0,0,0,0,0,0,1,1,1,0,0,0], 
 [0,1,1,0,1,0,0,0,0,0,0,0,0], 
 [0,1,0,0,1,1,0,0,1,0,1,0,0], 
 [0,1,0,0,1,1,0,0,1,1,1,0,0], 
 [0,0,0,0,0,0,0,0,0,0,1,0,0], 
 [0,0,0,0,0,0,0,1,1,1,0,0,0], 
 [0,0,0,0,0,0,0,1,1,0,0,0,0]]      

Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

Example 2: 
 [[0,0,0,0,0,0,0,0]]      

Given the above grid, return 0.

Note: The length of each dimension in the given grid does not exceed 50.

class Solution {
    public int maxAreaOfIsland(int[][] grid) {
        boolean[][] visited = new boolean[grid.length][grid[0].length];
        int max = 0;
        for(int i=0; i<grid.length; i++) {
            for(int j=0; j<grid[i].length; j++) {
                if (!visited[i][j] && grid[i][j] == 1) {
                    visited[i][j] = true;
                    int localMax = localMaxAreaOfIsland(grid, visited, i, j) + 1;
                    max = localMax > max ? localMax : max;
                }
            }
        }
        return max;
    }

    private int localMaxAreaOfIsland(int[][] grid, boolean[][] visited, int r, int c){
        int localMax = 0;
        if (r-1 >= 0 && !visited[r-1][c] && grid[r-1][c] == 1) {
            visited[r-1][c] = true;
            localMax = localMax + localMaxAreaOfIsland(grid, visited, r-1, c) + 1;
        } //move up
        if (c+1 < grid[r].length && !visited[r][c+1] && grid[r][c+1] == 1) {
            visited[r][c+1] = true;
            localMax = localMax + localMaxAreaOfIsland(grid, visited, r, c+1) + 1;
        } //move right
        if (r+1 < grid.length && !visited[r+1][c] && grid[r+1][c] == 1) {
            visited[r+1][c] = true;
            localMax = localMax + localMaxAreaOfIsland(grid, visited, r+1, c) + 1;
        } //move down
        if (c-1 >= 0 && !visited[r][c-1] && grid[r][c-1] == 1) {
            visited[r][c-1] = true;
            localMax = localMax + localMaxAreaOfIsland(grid, visited, r, c-1) + 1;
        } //move left
        return