Skip to content

Commit b2c1388

Browse files
week9 mission - Number of Islands
1 parent a36214c commit b2c1388

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
- ๋ฌธ์ œ: https://leetcode.com/problems/number-of-islands/
2+
- ํ’€์ด: https://algorithm.jonghoonpark.com/2024/03/31/leetcode-200
3+
4+
```java
5+
class Solution {
6+
public int numIslands(char[][] grid) {
7+
int w = grid.length;
8+
int h = grid[0].length;
9+
10+
int count = 0;
11+
for (int i = 0; i < w; i++) {
12+
for (int j = 0; j < h; j++) {
13+
if (grid[i][j] == '1') {
14+
dfs(grid, i,j);
15+
count++;
16+
}
17+
}
18+
}
19+
return count;
20+
}
21+
22+
public void dfs(char[][] grid, int i, int j) {
23+
if(i < 0 || i >= w || j < 0 || j >= h || grid[i][j] == '0') {
24+
return;
25+
}
26+
27+
grid[i][j] = '0';
28+
29+
dfs(grid, i-1, j);
30+
dfs(grid, i, j-1);
31+
dfs(grid, i+1, j);
32+
dfs(grid, i, j+1);
33+
}
34+
}
35+
```
36+
37+
## TC, SC
38+
39+
์ฝ”๋“œ์— ์ •์˜ํ•œ ๋Œ€๋กœ grid์˜ ๊ธธ์ด๋ฅผ `w`, grid[0]์˜ ๊ธธ์ด๋ฅผ `h`๋กœ ์ •์˜ํ–ˆ์„ ๋•Œ,
40+
์ด ์ฝ”๋“œ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(w \* h), ๊ณต๊ฐ„ ๋ณต์žก๋„๋Š” O(w \* h) ์ด๋‹ค.

0 commit comments

Comments
ย (0)