-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfind_cut_points.rs
74 lines (66 loc) · 1.81 KB
/
find_cut_points.rs
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
use std::collections::HashSet;
use crate::graph::Graph;
/// # Interface of find cur points
///
/// Must provide a special `fn bridges()` to achieve bridges of one graph
pub trait FindCutPoints {
fn cut_points(&mut self) -> Vec<usize>;
}
pub struct FindCutPointsImpl {
g: Graph,
visited: Vec<bool>,
ord: Vec<usize>,
low: Vec<usize>,
cnt: usize,
res: HashSet<usize>,
calculated: bool,
}
impl FindCutPointsImpl {
pub fn new(g: Graph) -> Self {
let v = g.v();
Self {
g,
visited: vec![false; v],
ord: vec![0; v],
low: vec![0; v],
cnt: 0,
res: HashSet::new(),
calculated: false,
}
}
fn dfs(&mut self, v: usize, parent: usize) {
self.visited[v] = true;
self.ord[v] = self.cnt;
self.low[v] = self.cnt;
self.cnt += 1;
let mut child = 0;
for w in self.g.adj_edge(v) {
if !self.visited[w] {
self.dfs(w, v);
self.low[v] = usize::min(self.low[v], self.low[w]);
if v != parent && self.low[w] >= self.ord[v] {
self.res.insert(v);
}
child += 1;
if v == parent && child > 1 {
self.res.insert(v);
}
} else if w != parent {
self.low[v] = usize::min(self.low[v], self.low[w]);
}
}
}
}
impl FindCutPoints for FindCutPointsImpl {
fn cut_points(&mut self) -> Vec<usize> {
if !self.calculated {
for w in 0..self.g.v() {
if !self.visited[w] {
self.dfs(w, w);
}
}
self.calculated = true;
}
self.res.clone().into_iter().collect()
}
}