let maxAreaOfIsland = function(grid) {
if (!grid || !grid.length) return 0;
let max = 0,
maxRow = grid.length,
maxCol = grid[0].length,
LAND = 1, VISITED = 2;
function markAndGetTotal(row, col) {
if (row < 0 || row >= maxRow || col < 0 || col >= maxCol) return 0;
if (grid[row][col] === LAND) {
grid[row][col] = VISITED;
let result = 1;
// top
result += markAndGetTotal(row - 1, col);
// bottom
result += markAndGetTotal(row + 1, col);
// left
result += markAndGetTotal(row, col - 1);
/// right
result += markAndGetTotal(row, col + 1);
return result;
}
return 0;
}
for (let row = 0; row < maxRow;row++) {
for (let col = 0; col < maxCol;col++) {
if (grid[row][col] === LAND) {
const total = markAndGetTotal(row, col); //?
max = Math.max(total, max);
}
}
}
return max;
};
Categories