-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgraph.rs
102 lines (85 loc) · 2.47 KB
/
graph.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
use core::panic;
use std::collections::hash_set::Iter;
use std::collections::HashSet;
use std::fmt::{Display, Formatter};
use std::fs;
#[derive(Debug)]
pub struct Graph {
v: usize,
e: usize,
adj: Vec<HashSet<usize>>,
}
impl Graph {
pub fn from(filename: &str) -> Self {
let file = fs::read_to_string(filename).unwrap();
let mut iter = file.split('\n');
let mut first_line = iter.next().unwrap().split_whitespace();
let v = first_line.next().unwrap().parse::<usize>().unwrap();
let e = first_line.next().unwrap().parse::<usize>().unwrap();
let mut ret = Graph {
v,
e,
adj: vec![HashSet::new(); v as usize],
};
for line in iter {
if line.is_empty() {
break;
}
let mut line = line.split_whitespace();
let x = line.next().unwrap().parse::<usize>().unwrap();
let y = line.next().unwrap().parse::<usize>().unwrap();
ret.validate_vertex(x);
ret.validate_vertex(y);
if x == y {
panic!("Self Loop is Detected!");
}
if ret.adj[x].contains(&y) {
panic!("Parallel Edges are Detected!");
}
ret.adj[x].insert(y);
ret.adj[y].insert(x);
}
ret
}
pub fn e(&self) -> usize {
self.e
}
pub fn v(&self) -> usize {
self.v
}
pub fn has_edge(&self, v1: usize, v2: usize) -> bool {
self.validate_vertex(v1);
self.validate_vertex(v2);
self.adj[v1].contains(&v2)
}
fn validate_vertex(&self, v: usize) {
if v >= self.v as usize {
panic!("vertex {} is not valid", v);
}
}
pub fn adj_edge(&self, v: usize) -> Iter<'_, usize> {
self.validate_vertex(v);
self.adj[v].iter()
}
pub fn degree(&self, v: usize) -> usize {
self.validate_vertex(v);
self.adj[v].len()
}
}
impl Display for Graph {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut list = String::new();
for v in 0..self.v {
list.push_str(format!("{}: ", v).as_str());
for w in &self.adj[v] {
list.push_str(format!("{} ", w).as_str());
}
list.push('\n');
}
write!(
f,
"AdjList: \nV: {}, E: {}\nList: \n{}",
self.v, self.e, list
)
}
}