File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * 2차원 배열을 돌며 상하좌우로 이동할 수 연속하여 이동할 수 있는 공간(섬) 찾기
3+ * @param {sting[][] } grid - 2차원 배열
4+ * @returns {number } 만들 수 있는 공간(섬)의 갯수
5+ *
6+ * 시간 복잡도: O(n * m)
7+ * m == grid.length
8+ * n == grid[i].length
9+ *
10+ * 공간 복잡도: O(n * m)
11+ * m == grid.length
12+ * n == grid[i].length
13+ */
14+ function numIslands ( grid : string [ ] [ ] ) : number {
15+ // 방문 배열 생성
16+ const visited : boolean [ ] [ ] = Array . from (
17+ { length : grid . length } ,
18+ ( ) => Array ( grid [ 0 ] . length ) . fill ( false )
19+ ) ;
20+
21+ let islands = 0 ;
22+
23+ const bfs = ( i : number , j : number ) : void => {
24+ // 방문 처리
25+ visited [ i ] [ j ] = true ;
26+
27+ // 상, 하, 좌, 우
28+ const directions : [ number , number ] [ ] = [
29+ [ - 1 , 0 ] ,
30+ [ 1 , 0 ] ,
31+ [ 0 , - 1 ] ,
32+ [ 0 , 1 ] ,
33+ ] ;
34+
35+ for ( const direction of directions ) {
36+ const nextI = i + direction [ 0 ] ;
37+ const nextJ = j + direction [ 1 ] ;
38+ if (
39+ nextI >= 0 &&
40+ nextI < grid . length &&
41+ nextJ >= 0 &&
42+ nextJ < grid [ 0 ] . length &&
43+ ! visited [ nextI ] [ nextJ ] &&
44+ grid [ nextI ] [ nextJ ] === '1'
45+ ) {
46+ bfs ( nextI , nextJ ) ;
47+ }
48+ }
49+ } ;
50+
51+ for ( let i = 0 ; i < grid . length ; i ++ ) {
52+ for ( let j = 0 ; j < grid [ 0 ] . length ; j ++ ) {
53+ if ( grid [ i ] [ j ] === '1' && ! visited [ i ] [ j ] ) {
54+ // 새로운 섬 발견
55+ islands ++ ;
56+
57+ // BFS 실행
58+ bfs ( i , j ) ;
59+ }
60+ }
61+ }
62+
63+ return islands ;
64+ }
65+
You can’t perform that action at this time.
0 commit comments