-
Notifications
You must be signed in to change notification settings - Fork 0
/
components.rs
140 lines (108 loc) · 2.99 KB
/
components.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
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use std::collections::{HashMap, HashSet, VecDeque};
type Id = i32;
struct Vertex {
id: Id,
neighbors: Vec<Id>,
}
impl Vertex {
fn new(id: Id) -> Self {
Vertex {
id,
neighbors: Vec::new(),
}
}
fn add_neighbor(&mut self, v: Id) {
self.neighbors.push(v);
}
fn preprocess(&self) {
//println!("preprocess: {}", self.id);
}
fn postprocess(&self) {
//println!("postprocess: {}", self.id);
}
}
struct Graph {
visited: HashSet<Id>,
processed: HashSet<Id>,
vertices: HashMap<Id, Vertex>,
}
impl Graph {
fn new() -> Self {
Graph {
visited: HashSet::new(),
processed: HashSet::new(),
vertices: HashMap::new(),
}
}
fn print(&self) {
println!("Num Vertices: {}", self.vertices.len());
for (id, node) in &self.vertices {
//println!("{}: {}", id, node.neighbors.len());
}
}
fn add_edge(&mut self, x: Id, y: Id) {
self.vertices
.entry(x)
.or_insert(Vertex::new(x))
.add_neighbor(y);
self.vertices
.entry(y)
.or_insert(Vertex::new(y))
.add_neighbor(x);
}
fn process_edge(&self, x: Id, y: Id, path: &mut Vec<Id>) {
path.push(y);
//println!("process edge: ({}, {})", x, y);
}
fn components(&mut self) -> Vec<HashSet<Id>> {
let mut comps: Vec<HashSet<Id>> = vec![];
for v in 0..self.vertices.len() {
let id = v as Id;
if !self.visited.contains(&id) {
//println!("{}", id);
let mut component = HashSet::new();
self.bfs(id, &mut component);
comps.push(component);
}
}
comps
}
fn bfs(&mut self, start: Id, component: &mut HashSet<Id>) -> Option<Vec<Id>> {
let mut q = VecDeque::new();
q.push_back(start);
self.visited.insert(start);
component.insert(start);
let mut path = vec![start];
while let Some(curr) = q.pop_front() {
let node = match self.vertices.get(&curr) {
None => continue,
Some(v) => v,
};
node.preprocess();
self.processed.insert(curr);
for &n in &node.neighbors {
if !self.visited.contains(&n) {
q.push_back(n);
self.visited.insert(n);
component.insert(n);
self.process_edge(curr, n, &mut path);
}
}
node.postprocess();
}
Some(path)
}
}
fn main() {
let mut g = Graph::new();
g.add_edge(0, 1);
g.add_edge(1, 2);
g.add_edge(2, 3);
g.add_edge(4, 5);
g.print();
//println!("");
//println!("Components: {:?}", g.components());
let mut c = HashSet::new();
let path = g.bfs(0, &mut c);
//println!("Path: {:?}", path);
}