-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1020.Number of enclaves
71 lines (69 loc) · 1.57 KB
/
1020.Number of enclaves
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
67
68
69
70
71
class Solution {
class Pair{
int fi;
int si;
Pair(int fst,int sec)
{
this.fi=fst;
this.si=sec;
}
}
public int numEnclaves(int[][] grid) {
int n=grid.length;
int m=grid[0].length;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{ if(i==0||i==n-1||j==0||j==m-1){
if(grid[i][j]==1)
{
bfs(grid,i,j);
}
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
System.out.print(grid[i][j]+" ");
}
System.out.println();
}
int c=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(grid[i][j]==1)
{
c+=1;
}
}
}
return c;
}
void bfs(int[][] grid,int i,int j)
{
int n=grid.length;
int m=grid[0].length;
Queue<Pair> qu=new LinkedList<>();
grid[i][j]=2;
qu.add(new Pair(i,j));
while(!qu.isEmpty())
{
Pair pi=qu.poll();
int row[]={-1,1,0,0};
int col[]={0,0,-1,1};
for(int k=0;k<4;k++){
int nrow=row[k]+pi.fi;
int ncol=col[k]+ pi.si;
if(nrow>=0 && nrow<=n-1 && ncol>=0 && ncol<=m-1 && grid[nrow][ncol]==1)
{
grid[nrow][ncol]=2;
qu.add(new Pair(nrow,ncol));
}
}
}
}
}