The maximum area Leetcode 695. islands

Given a two-dimensional array of non-null grid number 0 and 1, is an island formed of a combination of four directions (horizontal or vertical) 1 (representing the land). You can assume that the four edges of the two-dimensional matrix are surrounded by water.

Find a given two-dimensional array in the largest island in the area. (If there are no islands, the area is returned to 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]]
for the above should return the given matrix 6. Note that the answer should not be 11, since the islands comprise only four horizontal or vertical direction is '1'.

Example 2:

[[0,0,0,0,0,0,0,0]]
For the above given matrix, 0 is returned.

Note: The length and width of the given grid matrix is ​​not more than 50.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/max-area-of-island

Javascript code to achieve:

/**
 * @param {number[][]} grid
 * @return {number}
 */
var max = 0;
var visited = [];
var fillVisited = function(leni, lenj){
    for(let i = 0; i < leni; i++){
        visited[i] = [];
        for(let j = 0; j < lenj; j++){
            visited [I] .push ( 0); // whole array 0 
        }
    }
    return visited;
};
var maxAreaOfIsland = function(grid) {
    let maxx = 0;
    visited = fillVisited(grid.length, grid[0].length);// 行数和列数
    for(let i = 0; i < grid.length; i++){
        for(let j = 0; j < grid[0].length; j++){
            if(grid[i][j] == 1){
                max = 0;
                let ans = check(grid, i, j);
                if(maxx < ans){
                    maxx = years;
                }
            }
        }
    }
    return maxx;
};
var check = function(grid,i,j){
    if(!(i>=0 && i<grid.length && j>=0 && j<grid[0].length)||grid[i][j]!=1||visited[i][j])
        return 0;
    visited[i][j] = 1;
    return check(grid,i,j-1)+check(grid,i,j+1)+ check(grid,i-1,j)+check(grid,i+1,j)+1;
};

 

Guess you like

Origin www.cnblogs.com/ZLDJ-15-516/p/11027235.html