File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * ์ฃผ์ด์ง 2์ฐจ์ ๊ฒฉ์์์ ์ฌ์ ๊ฐ์๋ฅผ ๋ฐํํ๋ ํจ์
3
+ * ์๊ฐ๋ณต์ก๋: O(m * n) (๋ชจ๋ ์์๋ฅผ ์ํํด์ผ ํจ)
4
+ * ๊ณต๊ฐ๋ณต์ก๋: O(m * n) (bfs์ ๊ณต๊ฐ๋ณต์ก๋์ ๋ฐ๋ฆ)
5
+ * @param {character[][] } grid
6
+ * @return {number }
7
+ */
8
+ const numIslands = function ( grid ) {
9
+ let num = 0 ;
10
+
11
+ for ( let r = 0 ; r < grid . length ; r ++ ) {
12
+ for ( let c = 0 ; c < grid [ 0 ] . length ; c ++ ) {
13
+ if ( grid [ r ] [ c ] === '1' ) {
14
+ bfs ( grid , r , c ) ;
15
+ num += 1 ;
16
+ }
17
+ }
18
+ }
19
+
20
+ return num ;
21
+ } ;
22
+
23
+ // grid์ ์ฃผ์ด์ง ์ขํ์์ bfs๋ฅผ ์ํํด ๋ฐฉ๋ฌธํ์์ ํ์
24
+ // ์๊ฐ๋ณต์ก๋: O(m * n) (์ต์
์ ๊ฒฝ์ฐ ๋ชจ๋ ์์ ์ํ)
25
+ // ๊ณต๊ฐ๋ณต์ก๋: O(m * n) (์ต์
์ ๊ฒฝ์ฐ queue์ ๋ชจ๋ ์์ ์ ์ฅ)
26
+ function bfs ( grid , x , y ) {
27
+ const queue = [ [ x , y ] ] ;
28
+ const dx = [ 0 , 0 , 1 , - 1 ] ;
29
+ const dy = [ 1 , - 1 , 0 , 0 ] ;
30
+ const rows = grid . length ;
31
+ const cols = grid [ 0 ] . length ;
32
+
33
+ while ( queue . length ) {
34
+ const [ r , c ] = queue . shift ( ) ;
35
+
36
+ for ( let i = 0 ; i < 4 ; i ++ ) {
37
+ const nr = r + dx [ i ] ;
38
+ const nc = c + dy [ i ] ;
39
+
40
+ if ( 0 <= nr && nr < rows && 0 <= nc && nc < cols && grid [ nr ] [ nc ] === '1' ) {
41
+ queue . push ( [ nr , nc ] ) ;
42
+ grid [ nr ] [ nc ] = '0' ;
43
+ }
44
+ }
45
+ }
46
+ }
You canโt perform that action at this time.
0 commit comments