File tree 1 file changed +58
-0
lines changed
1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/number-of-islands/
3
+ * 풀이방법: BFS를 사용하여 섬의 개수를 구함
4
+ *
5
+ * 시간복잡도: O(n * m) (n: 그리드의 행, m: 그리드의 열)
6
+ * 공간복잡도: O(n * m) (그리드의 모든 요소를 방문)
7
+ */
8
+
9
+ function numIslands ( grid : string [ ] [ ] ) : number {
10
+ if ( ! grid . length ) return 0 ; // 그리드가 비어있는 경우
11
+
12
+ const rows = grid . length ;
13
+ const cols = grid [ 0 ] . length ;
14
+ let islands = 0 ;
15
+
16
+ const bfs = ( startRow : number , startCol : number ) => {
17
+ const q : number [ ] [ ] = [ [ startRow , startCol ] ] ;
18
+ grid [ startRow ] [ startCol ] = "0" ;
19
+
20
+ const directions = [
21
+ [ 1 , 0 ] ,
22
+ [ - 1 , 0 ] ,
23
+ [ 0 , 1 ] ,
24
+ [ 0 , - 1 ] ,
25
+ ] ; // 상하좌우
26
+
27
+ while ( q . length ) {
28
+ const [ r , c ] = q . shift ( ) ! ;
29
+
30
+ for ( const [ dx , dy ] of directions ) {
31
+ const newR = r + dx ;
32
+ const newC = c + dy ;
33
+
34
+ if (
35
+ newR >= 0 &&
36
+ newR < rows &&
37
+ newC >= 0 &&
38
+ newC < cols &&
39
+ grid [ newR ] [ newC ] === "1"
40
+ ) {
41
+ q . push ( [ newR , newC ] ) ;
42
+ grid [ newR ] [ newC ] = "0" ;
43
+ }
44
+ }
45
+ }
46
+ } ;
47
+
48
+ for ( let r = 0 ; r < rows ; r ++ ) {
49
+ for ( let c = 0 ; c < cols ; c ++ ) {
50
+ if ( grid [ r ] [ c ] === "1" ) {
51
+ islands ++ ;
52
+ bfs ( r , c ) ;
53
+ }
54
+ }
55
+ }
56
+
57
+ return islands ;
58
+ }
You can’t perform that action at this time.
0 commit comments