Skip to content

Commit 23ee851

Browse files
authored
Create shortest-cycle-in-a-graph.cpp
1 parent 115fca9 commit 23ee851

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

C++/shortest-cycle-in-a-graph.cpp

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Time: O(n^2)
2+
// Space: O(n + e)
3+
4+
// bfs
5+
class Solution {
6+
public:
7+
int findShortestCycle(int n, vector<vector<int>>& edges) {
8+
static const int INF = numeric_limits<int>::max();
9+
10+
vector<vector<int>> adj(n);
11+
for (const auto& e : edges) {
12+
adj[e[0]].emplace_back(e[1]);
13+
adj[e[1]].emplace_back(e[0]);
14+
}
15+
const auto& bfs = [&](int u) {
16+
vector<int> dist(n, INF);
17+
vector<int> q = {u};
18+
dist[u] = 0;
19+
while (!empty(q)) {
20+
vector<int> new_q;
21+
for (const auto& u : q) {
22+
for (const auto& v : adj[u]) {
23+
if (dist[v] == dist[u] - 1) {
24+
continue;
25+
}
26+
if (dist[v] != INF) {
27+
return 1 + dist[u] + dist[v];
28+
}
29+
dist[v] = dist[u] + 1;
30+
new_q.emplace_back(v);
31+
}
32+
}
33+
q = move(new_q);
34+
}
35+
return INF;
36+
};
37+
38+
int result = INF;
39+
for (int u = 0; u < n; ++u) {
40+
result = min(result, bfs(u));
41+
}
42+
return result != INF ? result : -1;
43+
}
44+
};

0 commit comments

Comments
 (0)