-
Notifications
You must be signed in to change notification settings - Fork 77
/
solution.cpp
82 lines (76 loc) · 2.42 KB
/
solution.cpp
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
class Solution {
public:
int shortestBridge(vector<vector<int>>& A) {
queue<pair<int,int> > que;
bool found = false;
for(int i=0;i<A.size();i++){
for(int j=0;j<A[0].size();j++){
if(A[i][j] == 1){
found = true;
dfs(A, i,j,que);
break;
}
}
if(found)
break;
}
int x,y,step=0;
while(que.size() != 0){
int size = que.size();
for(int i=0;i<size;i++){
x = que.front().first;
y = que.front().second;
que.pop();
if(x-1>=0 && A[x-1][y] != 2){
if(A[x-1][y] == 0){
A[x-1][y] = 2;
que.push(pair<int,int>(x-1,y));
}else if(A[x-1][y] == 1){
return step;
}
}
if(x+1<A.size() && A[x+1][y] != 2){
if(A[x+1][y] == 0){
A[x+1][y] = 2;
que.push(pair<int,int>(x+1,y));
}else if(A[x+1][y] == 1){
return step;
}
}
if(y-1>=0 && A[x][y-1] != 2){
if(A[x][y-1] == 0){
A[x][y-1] = 2;
que.push(pair<int,int>(x,y-1));
}else if(A[x][y-1] == 1){
return step;
}
}
if(y+1<A[0].size() && A[x][y+1] != 2){
if(A[x][y+1] == 0){
A[x][y+1] = 2;
que.push(pair<int,int>(x,y+1));
}else if(A[x][y+1] == 1){
return step;
}
}
}
step += 1;
}
return step;
}
int dfs(vector<vector<int>>& A, int x, int y, queue<pair<int,int> > & que){
if(A[x][y] == 1){
que.push(pair<int,int>(x,y));
A[x][y] = 2;
if(x-1>=0)
dfs(A, x-1,y,que);
if(x+1<A.size())
dfs(A, x+1,y,que);
if(y-1>=0)
dfs(A, x,y-1,que);
if(y+1<A[0].size())
dfs(A, x,y+1,que);
}
return 0;
}
};