File tree 1 file changed +66
-0
lines changed
1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Title: Number of Enclaves
3
+ * Description: You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell.
4
+ * Author: Hasibul Islam
5
+ * Date: 07/04/2023
6
+ */
7
+
8
+ /**
9
+ * @param {number[][] } grid
10
+ * @return {number }
11
+ */
12
+ function numEnclaves ( grid ) {
13
+ const m = grid . length ;
14
+ const n = grid [ 0 ] . length ;
15
+ const visited = Array ( m )
16
+ . fill ( )
17
+ . map ( ( ) => Array ( n ) . fill ( false ) ) ;
18
+
19
+ // mark all boundary land cells as reachable
20
+ for ( let i = 0 ; i < m ; i ++ ) {
21
+ dfs ( i , 0 ) ;
22
+ dfs ( i , n - 1 ) ;
23
+ }
24
+ for ( let j = 0 ; j < n ; j ++ ) {
25
+ dfs ( 0 , j ) ;
26
+ dfs ( m - 1 , j ) ;
27
+ }
28
+
29
+ // count the number of unreachable land cells
30
+ let count = 0 ;
31
+ for ( let i = 0 ; i < m ; i ++ ) {
32
+ for ( let j = 0 ; j < n ; j ++ ) {
33
+ if ( grid [ i ] [ j ] === 1 && ! visited [ i ] [ j ] ) {
34
+ count ++ ;
35
+ }
36
+ }
37
+ }
38
+ return count ;
39
+
40
+ function dfs ( i , j ) {
41
+ if (
42
+ i < 0 ||
43
+ i >= m ||
44
+ j < 0 ||
45
+ j >= n ||
46
+ visited [ i ] [ j ] ||
47
+ grid [ i ] [ j ] === 0
48
+ ) {
49
+ return ;
50
+ }
51
+ visited [ i ] [ j ] = true ;
52
+ dfs ( i - 1 , j ) ;
53
+ dfs ( i + 1 , j ) ;
54
+ dfs ( i , j - 1 ) ;
55
+ dfs ( i , j + 1 ) ;
56
+ }
57
+ }
58
+
59
+ const grid = [
60
+ [ 0 , 0 , 0 , 0 ] ,
61
+ [ 1 , 0 , 1 , 0 ] ,
62
+ [ 0 , 1 , 1 , 0 ] ,
63
+ [ 0 , 0 , 0 , 0 ] ,
64
+ ] ;
65
+
66
+ console . log ( numEnclaves ( grid ) ) ; // Output: 3
You can’t perform that action at this time.
0 commit comments