Number of Enclaves LeetCode solution in Java

1
class Solution {
2
public int numEnclaves(int[][] grid) {
3
int maxcount = 0;
4
// if(grid.length==10)
5
// {
6
// return 3;
7
// }
8
for (int i = 0; i < grid.length; i++) {
9
for (int j = 0; j < grid[0].length; j++) {
10
if (grid[i][j] == 0) {
11
continue;
12
}
13
if (i == 0 || i == grid.length - 1 || j == grid[0].length - 1 || j == 0) {
14
dfs(grid, i, j);
15
}
16
}
17
}
18
int count = 0;
19
for (int i = 0; i < grid.length; i++) {
20

21
for (int j = 0; j < grid[0].length; j++) {
22

23
if (grid[i][j] == 1) {
24
count++;
25
}
26
}
27
}
28

29
return count;
30
}
31

32
int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
33

34
public void dfs(int[][] grid, int row, int col) {
35

36
grid[row][col] = 0;
37
for (int k = 0; k < 4; k++) {
38
int rowdash = row + dirs[k][0];
39
int coldash = col + dirs[k][1];
40

41
if (rowdash < 0
42
|| coldash < 0
43
|| rowdash >= grid.length
44
|| coldash >= grid[0].length
45
|| grid[rowdash][coldash] == 0) {
46
continue;
47
}
48

49
if (grid[rowdash][coldash] == 1) {
50
dfs(grid, rowdash, coldash);
51
}
52
}
53
}
54
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0