File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ *@link https://leetcode.com/problems/number-of-islands/
3
+ *
4
+ * ์ ๊ทผ ๋ฐฉ๋ฒ :
5
+ * - ์ฌ์ ์์์ ์์ ๋๊น์ง ํ์ํด์ผ ํ๋ฏ๋ก DFS ์ฌ์ฉ
6
+ * - ๋ฐฉ๋ฌธํ ์ฌ์ ์ค๋ณต ํ์ ๋ฐฉ์งํ๊ธฐ ์ํด์ ๋ฐฉ๋ฌธ ํ ๊ฐ ๋ณ๊ฒฝ ์ฒ๋ฆฌ
7
+ *
8
+ * ์๊ฐ๋ณต์ก๋ : O(m * n)
9
+ * - 2์ฐจ์ ๋ฐฐ์ด ์ ์ฒด๋ฅผ ์ํํ๋ฏ๋ก O(m * n)
10
+ *
11
+ * ๊ณต๊ฐ๋ณต์ก๋ : O(m * n)
12
+ * - DFS ํธ์ถ ์คํ ์ต๋ ๊น์ด๊ฐ m * n ๋งํผ ์์ผ ์ ์๋ค.
13
+ */
14
+
15
+ function numIslands ( grid : string [ ] [ ] ) : number {
16
+ let count = 0 ;
17
+ const rows = grid . length ;
18
+ const cols = grid [ 0 ] . length ;
19
+
20
+ // ์ํ์ข์ฐ ํ์ ๋ฐฉํฅ ๋ฐฐ์ด
21
+ const directions = [
22
+ [ 0 , - 1 ] ,
23
+ [ 0 , 1 ] ,
24
+ [ - 1 , 0 ] ,
25
+ [ 1 , 0 ] ,
26
+ ] ;
27
+
28
+ // ํ์ฌ ์์น์์ ์ฐ๊ฒฐ๋ ๋ชจ๋ ์ฌ ํ์
29
+ const dfs = ( row : number , col : number ) => {
30
+ // ์ข
๋ฃ ์กฐ๊ฑด : ๋ฒ์ ๋ฒ์ด๋๊ฑฐ๋, ์ด๋ฏธ ๋ฐฉ๋ฌธํ ๊ฒฝ์ฐ
31
+ if (
32
+ row < 0 ||
33
+ row >= rows ||
34
+ col < 0 ||
35
+ col >= cols ||
36
+ grid [ row ] [ col ] === "0"
37
+ )
38
+ return ;
39
+
40
+ // ํ์ฌ ์์น ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ
41
+ grid [ row ] [ col ] = "0" ;
42
+
43
+ // ์ํ์ข์ฐ ํ์
44
+ for ( const [ x , y ] of directions ) {
45
+ dfs ( row + x , col + y ) ;
46
+ }
47
+ } ;
48
+
49
+ for ( let row = 0 ; row < rows ; row ++ ) {
50
+ for ( let col = 0 ; col < cols ; col ++ ) {
51
+ // ์ฌ์ ์์์ ์ธ ๊ฒฝ์ฐ
52
+ if ( grid [ row ] [ col ] === "1" ) {
53
+ count ++ ;
54
+ dfs ( row , col ) ;
55
+ }
56
+ }
57
+ }
58
+
59
+ return count ;
60
+ }
You canโt perform that action at this time.
0 commit comments