-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
distance-to-a-cycle-in-undirected-graph.cpp
65 lines (61 loc) · 1.8 KB
/
distance-to-a-cycle-in-undirected-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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// Time: O(|V| + |E|)
// Space: O(|V| + |E|)
// graph, dfs, bfs
class Solution {
public:
vector<int> distanceToCycle(int n, vector<vector<int>>& edges) {
vector<vector<int>> adj(n);
for (const auto& e : edges) {
adj[e[0]].emplace_back(e[1]);
adj[e[1]].emplace_back(e[0]);
}
return bfs(adj, iter_dfs(adj));
}
private:
vector<int> cycle(const vector<int>& parent, int v, int u) {
vector<int> result = {parent[v], v};
for (; u != parent[v]; u = parent[u]) {
result.emplace_back(u);
}
return result;
}
vector<int> iter_dfs(const vector<vector<int>>& adj) {
vector<int> stk = {0};
vector<int> parent(size(adj), -2);
parent[0] = -1;
while (!empty(stk)) {
const int u = stk.back(); stk.pop_back();
for (const auto& v : adj[u]) {
if (parent[v] != -2) {
if (v == parent[u]) {
continue;
}
return cycle(parent, v, u);
}
parent[v] = u;
stk.emplace_back(v);
}
}
return {};
}
vector<int> bfs(const vector<vector<int>>& adj, vector<int> q) {
vector<int> result(size(adj), -1);
for (const auto& x : q) {
result[x] = 0;
}
for (int d = 1; !empty(q); ++d) {
vector<int> new_q;
for (const auto& u : q) {
for (const auto& v : adj[u]) {
if (result[v] != -1) {
continue;
}
result[v] = d;
new_q.emplace_back(v);
}
}
q = move(new_q);
}
return result;
}
};