forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain2.cpp
107 lines (85 loc) · 2.42 KB
/
main2.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/// Source : https://leetcode.com/problems/shortest-bridge/
/// Author : liuyubobobo
/// Time : 2018-11-03
#include <iostream>
#include <vector>
#include <queue>
#include <cassert>
using namespace std;
/// From all the nodes of one component,
/// get the shortest one to the other component,
/// Using BFS
/// We can put all the nodes in one component into the queue :-)
///
/// Time Complexity: O(m * n)
/// Space Complexity: O(m * n)
class Solution {
private:
int m, n;
const int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public:
int shortestBridge(vector<vector<int>>& A) {
m = A.size();
n = A[0].size();
for(int i = 0; i < m; i ++)
for(int j = 0; j < n; j ++)
if(A[i][j]){
floodfill(A, i, j);
return bfs(A);
}
assert(false);
return -1;
}
private:
int bfs(const vector<vector<int>>& A){
queue<int> q;
vector<bool> visited(m * n, false);
vector<int> prev(m * n, -1);
for(int i = 0; i < m; i ++)
for(int j = 0; j < n; j ++)
if(A[i][j] == 2){
q.push(i * n + j);
visited[i * n + j] = true;
}
int cur;
while(!q.empty()){
cur = q.front();
int curx = cur / n, cury = cur % n;
q.pop();
if(A[curx][cury] == 1)
break;
for(int i = 0; i < 4; i ++){
int nextx = curx + d[i][0], nexty = cury + d[i][1];
int next = nextx * n + nexty;
if(inArea(nextx, nexty) && !visited[next]){
visited[next] = true;
prev[next] = cur;
q.push(next);
}
}
}
int res = 0;
while(cur != -1){
if(!A[cur / n][cur % n])
res ++;
cur = prev[cur];
}
return res;
}
void floodfill(vector<vector<int>>& A, int x, int y){
A[x][y] = 2;
for(int i = 0; i < 4; i ++){
int nextx = x + d[i][0], nexty = y + d[i][1];
if(inArea(nextx, nexty)){
if(A[nextx][nexty] == 1)
floodfill(A, nextx, nexty);
}
}
}
bool inArea(int x, int y){
return x >= 0 && x < m && y >= 0 && y < n;
}
};
int main() {
return 0;
}