File tree 1 file changed +40
-0
lines changed
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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) ์ด๋ค.
You canโt perform that action at this time.
0 commit comments