LeetCode - Count Sub Islands (Javascript)

문제 설명

1번 그리드와 2번 그리드를 비교하여, 1번 그리드에 포함되는 2번에서의 섬의 개수를 구하는 문제다.

You are given two m x n binary matrices grid1 and grid2 containing only 0‘s (representing water) and 1‘s (representing land). An island is a group of 1‘s connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.

An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.

Return the *number of islands in* grid2 *that are considered sub-islands*.

Example 1:

https://assets.leetcode.com/uploads/2021/06/10/test1.png

1
2
3
4
Input: grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]
Output: 3
Explanation:In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.

Example 2:

https://assets.leetcode.com/uploads/2021/06/03/testcasex2.png

1
2
3
4
Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]
Output: 2
Explanation:In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.

Constraints:

  • m == grid1.length == grid2.length
  • n == grid1[i].length == grid2[i].length
  • 1 <= m, n <= 500
  • grid1[i][j] and grid2[i][j] are 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
const countSubIslands = (grid1, grid2) => {
let answer = 0;
for (let i = 0; i < grid1.length; i++) {
for (let j = 0; j < grid1[0].length; j++) {
// 1번 그리드는 0인데 2번 그리드는 1이라면? => dfs로 2번 그리드의 연결된 1들 삭제
if (grid1[i][j] === 0 && grid2[i][j] === 1) dfs(grid2, i, j);
}
}
for (let i = 0; i < grid1.length; i++) {
for (let j = 0; j < grid1[0].length; j++) {
// 위의 과정을 거쳤는데 grid2가 1이면 서브 아일랜드라는 뜻
if (grid2[i][j] === 1) {
dfs(grid2, i, j);
answer++; // 그만큼 answer++
}
}
}
return answer;
};

function dfs(grid, i, j) {
if (grid[i] === undefined || grid[i][j] === undefined || !grid[i][j]) return;
grid[i][j] = 0;
dfs(grid, i + 1, j); // up
dfs(grid, i, j + 1); // right
dfs(grid, i - 1, j); // down
dfs(grid, i, j - 1); // left
}


Author

Hoonjoo

Posted on

2022-04-13

Updated on

2022-04-13

Licensed under

Comments