LeetCode - Max Area of Island (Javascript)

Description

위에서 풀었던 문제와 굉장히 유사하다. 그냥 그 문제에서 최대 넓이만 구하면 되는 문제다!

You are given an m x n binary matrix grid. 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.

The area of an island is the number of cells with a value 1 in the island.

Return the maximum area of an island in grid. If there is no island, return 0.

Example 1:

https://assets.leetcode.com/uploads/2021/05/01/maxarea1-grid.jpg

1
2
3
Input: grid = [[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]]
Output: 6
Explanation: The answer is not 11, because the island must be connected 4-directionally.

Example 2:

1
2
Input: grid = [[0,0,0,0,0,0,0,0]]
Output: 0

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 50
  • grid[i][j] is either 0 or 1.

소스 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
function maxAreaOfIsland(grid) {
let answer = 0;
let count = 0;
const maxRow = grid.length - 1;
const maxColumn = grid[0].length - 1;

function traverse(row, col, grid) {
// 아래 조건에 해당되면 해당 노드의 값은 1이 아닌 것!
if (
grid[row] === undefined ||
grid[row][col] === undefined ||
grid[row][col] === 0
) {
return;
}
grid[row][col] = 0;
// 매 재귀 실행 시, 1을 찾을 때마다 count++을 해준다.
count++;
traverse(row - 1, col, grid);
traverse(row, col + 1, grid);
traverse(row + 1, col, grid);
traverse(row, col - 1, grid);
}

for (let i = 0; i <= maxRow; i++) {
for (let j = 0; j <= maxColumn; j++) {
if (grid[i][j] === 1) {
traverse(i, j, grid);
// 그리고 재귀가 끝났을 때, answer와 count 중 더 큰 값을 answer에 할당해준다.
answer = Math.max(answer, count);
// 그리고 다시 count는 0으로 초기화 해주면 된다.
count = 0;
}
}
}
return answer;
}

LeetCode - Max Area of Island (Javascript)

https://hoonjoo-park.github.io/algorithm/leet/maxAreaOfIslands/

Author

Hoonjoo

Posted on

2022-03-24

Updated on

2022-03-24

Licensed under

Comments