File tree 1 file changed +71
-0
lines changed
1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change
1
+ // w: width of grid, h: height of grid
2
+ // Time complexity: O(h*w)
3
+ // Space complexity: O(h*w)
4
+
5
+ class MyQueue {
6
+ constructor ( ) {
7
+ this . q = [ ] ;
8
+ this . front = 0 ;
9
+ this . rear = 0 ;
10
+ }
11
+
12
+ get isEmpty ( ) {
13
+ return this . front === this . rear ;
14
+ }
15
+
16
+ push ( value ) {
17
+ this . q . push ( value ) ;
18
+ this . rear ++ ;
19
+ }
20
+
21
+ pop ( ) {
22
+ const value = this . q [ this . front ] ;
23
+ delete this . q [ this . front ++ ] ;
24
+ return value ;
25
+ }
26
+ }
27
+
28
+ /**
29
+ * @param {character[][] } grid
30
+ * @return {number }
31
+ */
32
+ var numIslands = function ( grid ) {
33
+ const h = grid . length ;
34
+ const w = grid [ 0 ] . length ;
35
+
36
+ const dy = [ 1 , 0 , - 1 , 0 ] ;
37
+ const dx = [ 0 , 1 , 0 , - 1 ] ;
38
+
39
+ const bfs = ( start ) => {
40
+ const q = new MyQueue ( ) ;
41
+ q . push ( start ) ;
42
+ const [ sy , sx ] = start ;
43
+ grid [ sy ] [ sx ] = "0" ;
44
+
45
+ while ( ! q . isEmpty ) {
46
+ const [ cy , cx ] = q . pop ( ) ;
47
+
48
+ for ( let i = 0 ; i < dy . length ; i ++ ) {
49
+ const ny = cy + dy [ i ] ;
50
+ const nx = cx + dx [ i ] ;
51
+
52
+ if ( ny >= 0 && ny < h && nx >= 0 && nx < w && grid [ ny ] [ nx ] === "1" ) {
53
+ q . push ( [ ny , nx ] ) ;
54
+ grid [ ny ] [ nx ] = "0" ;
55
+ }
56
+ }
57
+ }
58
+ } ;
59
+
60
+ let answer = 0 ;
61
+ for ( let i = 0 ; i < h ; i ++ ) {
62
+ for ( let j = 0 ; j < w ; j ++ ) {
63
+ if ( grid [ i ] [ j ] === "1" ) {
64
+ answer ++ ;
65
+ bfs ( [ i , j ] ) ;
66
+ }
67
+ }
68
+ }
69
+
70
+ return answer ;
71
+ } ;
You can’t perform that action at this time.
0 commit comments