-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
shortest-cycle-in-a-graph.cpp
49 lines (46 loc) · 1.59 KB
/
shortest-cycle-in-a-graph.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
// Time: O(n^2)
// Space: O(n + e)
// bfs
class Solution {
public:
int findShortestCycle(int n, vector<vector<int>>& edges) {
static const int INF = numeric_limits<int>::max();
vector<vector<int>> adj(n);
for (const auto& e : edges) {
adj[e[0]].emplace_back(e[1]);
adj[e[1]].emplace_back(e[0]);
}
const auto& bfs = [&](int u) {
int result = INF;
vector<int> dist(n, INF);
dist[u] = 0;
vector<int> q = {u};
while (!empty(q)) {
vector<int> new_q;
for (const auto& u : q) {
for (const auto& v : adj[u]) {
if (dist[v] != INF) {
assert(abs(dist[v] - dist[u]) <= 1);
if (dist[v] != dist[u] - 1) {
result = min(result, 1 + dist[u] + dist[v]); // d = dist[u]+1 >= 2, check if any cycle of length 2*d-1 or 2*d exists
}
continue;
}
dist[v] = dist[u] + 1;
new_q.emplace_back(v);
}
}
if (result != INF) { // a cycle of length 2*d-1 or 2*d was found, early return
break;
}
q = move(new_q);
}
return result;
};
int result = INF;
for (int u = 0; u < n; ++u) {
result = min(result, bfs(u));
}
return result != INF ? result : -1;
}
};