728x90
https://leetcode.com/problems/max-area-of-island/submissions/
Max Area of Island - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
이중 배열을 돌면서 flood를 통하여 가장 넓은 영역의 섬의 면적을 리턴하는 문제이다.
이중 배열을 돌면서 그 값이 1인 경우 탐색을 시작한다.
var maxAreaOfIsland = function(grid) {
let maxArea = 0
const M = grid.length
const N = grid[0].length
const array = Array.from(Array(grid.length), () => new Array(grid[0].length).fill(false))
let compass = [[-1, 0], [0, -1], [1, 0], [0, 1]]
const isValid = (row, col) => row >= 0 && row < M && col >= 0 && col < N;
for (let i = 0; i < M; i++) {
for (let j = 0; j < N; j++) {
if (grid[i][j] === 1) {
flood([[i, j]])
}
}
}
return maxArea
function flood(stack) {
let currentArea = 0
while (stack.length) {
let [row, col] = stack.pop()
if (!isValid(row, col) || array[row][col] || grid[row][col] === 0) {
continue
}
currentArea++
array[row][col] = true
for (const direction of compass) {
stack.push([row + direction[0], col + direction[1]])
}
}
maxArea = Math.max(maxArea, currentArea)
}
};
if (!isValid(row, col) || array[row][col] || grid[row][col] === 0) {
continue
}
값이 유효하지 않거나, 방문했을 경우, 0일 경우 건너뛴다.
currentArea++
array[row][col] = true
그렇지 않을 경우 현재 영역을 +1 시키고 방문했다는 표시를 해준다.
for (const direction of compass) {
stack.push([row + direction[0], col + direction[1]])
}
상하좌우로 확인해주기 위하여 스택에 push 해준다.
maxArea = Math.max(maxArea, currentArea)
현재 영역의 값과 최대값을 비교하여 최대값에 재할당해준다.
728x90
'코테' 카테고리의 다른 글
큰 수 만들기 (0) | 2022.06.13 |
---|---|
[LeetCode] 617. Merge Two Binary Trees (0) | 2022.06.06 |
[leetcode] 1254. Number of Closed Islands (0) | 2022.06.04 |
애니어그램 (0) | 2022.05.16 |
짝지어 제거하기 (0) | 2022.05.14 |