-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathNumber of Enclaves.java
66 lines (54 loc) · 1.5 KB
/
Number of Enclaves.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Runtime: 11 ms (Top 84.26%) | Memory: 54.7 MB (Top 92.39%)
class Solution {
public int numEnclaves(int[][] grid) {
int maxcount = 0;
// if(grid.length==10)
// {
// return 3;
// }
for(int i = 0;i<grid.length;i++)
{
for(int j = 0;j<grid[0].length;j++)
{
if(grid[i][j] ==0)
{
continue;
}
if(i==0||i==grid.length-1||j==grid[0].length-1||j==0)
{
dfs(grid,i,j);
}
}
}
int count = 0;
for(int i = 0;i<grid.length;i++)
{
for(int j = 0;j<grid[0].length;j++)
{
if(grid[i][j]==1)
{
count++;
}
}
}
return count;
}
int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};
public void dfs(int[][] grid,int row,int col) {
grid[row][col] = 0;
for(int k = 0;k<4;k++)
{
int rowdash = row+dirs[k][0];
int coldash = col+dirs[k][1];
if(rowdash<0||coldash<0||rowdash>=grid.length||coldash>=grid[0].length||
grid[rowdash][coldash]==0)
{
continue;
}
if(grid[rowdash][coldash]==1)
{
dfs(grid,rowdash,coldash);
}
}
}
}