Skip to content

Commit 06d61ed

Browse files
committed
feat: 문제풀이 추가
1 parent fc5e333 commit 06d61ed

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

number-of-islands/hwanmini.js

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// 시간복잡도: O(n * m)
2+
// 공간복잡도: O(n * m)
3+
4+
const dr = [1,-1,0,0]
5+
const dc = [0,0,-1, 1]
6+
7+
const isValidMove = (grid, n_row, n_col) => {
8+
return n_row >= 0 && n_row < grid.length && n_col >= 0 && n_col < grid[0].length && grid[n_row][n_col] !== '0'
9+
}
10+
11+
12+
/**
13+
* @param {character[][]} grid
14+
* @return {number}
15+
*/
16+
var numIslands = function(grid) {
17+
let islandCount = 0;
18+
19+
const bfs = (row, col) => {
20+
const que = [[row,col]]
21+
22+
while (que.length) {
23+
const [row, col] = que.pop()
24+
25+
for (let i = 0 ; i < dr.length; i++) {
26+
const n_row = row + dr[i]
27+
const n_col = col + dc[i]
28+
29+
if (isValidMove(grid, n_row, n_col)) {
30+
que.push([n_row, n_col])
31+
}
32+
}
33+
34+
grid[row][col] = '0'
35+
36+
}
37+
38+
islandCount += 1
39+
}
40+
41+
42+
for (let row = 0; row < grid.length; row++) {
43+
for (let col = 0; col < grid[row].length; col++) {
44+
if (grid[row][col] !== '0') bfs(row, col)
45+
}
46+
}
47+
48+
49+
return islandCount
50+
};
51+
52+
console.log(numIslands([["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]))

0 commit comments

Comments
 (0)