-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path934. Shortest Bridge
93 lines (72 loc) · 2.21 KB
/
934. Shortest Bridge
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class Solution {
public:
// Time Complexity - O(k * r * c)
// Space Complexity - O(r * c)
// k is the number of cells representing the starting island
// r is the number of row
// c is the number of column
const int dx[4]={-1,1,0,0};
const int dy[4]={0,0,-1,1};
//boundary checks
bool isValid(int i,int j,int r,int c){
return (i<r && j<c && i>=0 && j>=0);
}
void changeIslandType(int i,int j,int r,int c,vector<vector<int>>& grid){
if(i>=r or j>=c or i<0 or j<0 or grid[i][j]==0 or grid[i][j]==2)return;
grid[i][j]=2;
for(int x=0;x<4;++x){
int nr=i+dx[x];
int nc=j+dy[x];
changeIslandType(nr,nc,r,c, grid);
}
}
int shortestBridge(vector<vector<int>>& grid) {
int r=grid.size();
int c=grid[0].size();
queue<pair<int,int>>q;
int change=0;
bool check=false;
//change the islands
for(int i=0;i<r;++i){
for(int j=0;j<c;++j){
if(grid[i][j]){
changeIslandType(i,j,r,c,grid);
check=true;
break;
}
}
if(check)
break;
}
//get the new islands in queue
for(int i=0;i<r;++i){
for(int j=0;j<c;++j){
if(grid[i][j]==2){
q.push({i,j});
}
}
}
while(!q.empty()){
change++;
int sz=q.size();
while(sz--){
auto node=q.front();
q.pop();
//4 directions
for(int x=0;x<4;++x){
int nr=node.first+dx[x];
int nc=node.second+dy[x];
if(isValid(nr,nc,r,c) ){
if( grid[nr][nc]==0){
grid[nr][nc]=2;
q.push({nr,nc});
}
if(grid[nr][nc]==1)
return change-1;
}
}
}
}
return 0;
}
};