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
給定一個非空的二維陣列網格為0和1,一個島是一組1(代表陸地)四方向(水平或垂直)。您可以假設網格的所有四個邊緣被水包圍。 在給定的2D數組中找到一個島的最大面積。 (如果沒有島,最大面積為0.)
解法:用廣度優先法遍歷值為1的坐標,用set保存已遍歷過的坐標
var maxAreaOfIsland = function (grid) {
let max = 0;
let posSet = new Set();
for (let r = 0; r < grid.length; r++) {
let row = grid[r];
for (let c = 0; c < row.length; c++) {
if (row[c] === 0 || posSet.has(getPosStr(r, c))) continue;
let block = 0;
let queue = [{ r, c }];
posSet.add(getPosStr(r, c));
while (queue.length > 0) {
block++;
let pos = queue.shift();
let posRow = pos.r;
let posCol = pos.c;
if (posRow >= 1 && grid[posRow - 1][posCol] == 1 && !posSet.has(getPosStr(posRow - 1, posCol))) {
queue.push({ r: posRow - 1, c: posCol });
posSet.add(getPosStr(posRow - 1, posCol));
}
if (posRow < grid.length - 1 && grid[posRow + 1][posCol] == 1 && !posSet.has(getPosStr(posRow + 1, posCol))) {
queue.push({ r: posRow + 1, c: posCol });
posSet.add(getPosStr(posRow + 1, posCol));
}
if (posCol >= 1 && grid[posRow][posCol - 1] == 1 && !posSet.has(getPosStr(posRow, posCol - 1))) {
queue.push({ r: posRow, c: posCol - 1 });
posSet.add(getPosStr(posRow, posCol - 1));
}
if (posCol < row.length - 1 && grid[posRow][posCol + 1] == 1 && !posSet.has(getPosStr(posRow, posCol + 1))) {
queue.push({ r: posRow, c: posCol + 1 });
posSet.add(getPosStr(posRow, posCol + 1));
}
}
max = Math.max(max, block);
}
}
return max;
};
let getPosStr = (x, y) => {
return x + "," + y;
}