implement bfs
This commit is contained in:
parent
268daf6c93
commit
edec1f208f
2 changed files with 51 additions and 2 deletions
51
src/graph.rs
51
src/graph.rs
|
@ -1,4 +1,5 @@
|
|||
use std::rc::Rc;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
const MAXV: usize = 1000;
|
||||
|
||||
|
@ -14,11 +15,21 @@ struct Edgenode {
|
|||
pub struct Graph {
|
||||
edges: Vec<Option<Rc<Edgenode>>>, // adjacency info
|
||||
degree: Vec<i32>, // outdegree of each vertex
|
||||
nvertices: i32, // number of vertices in graph
|
||||
nvertices: usize, // number of vertices in graph
|
||||
nedges: i32, // number of edges in graph
|
||||
directed: bool, // is the graph directed?
|
||||
}
|
||||
|
||||
struct BfsState {
|
||||
// A vertex is `discovered` the first time we visit it.
|
||||
discovered: Vec<bool>,
|
||||
// A vertex is `processed` after we have traversed all outgoing
|
||||
// edges from it.
|
||||
processed: Vec<bool>,
|
||||
// Discovery relation
|
||||
parent: Vec<i32>,
|
||||
}
|
||||
|
||||
impl Graph {
|
||||
pub fn new(directed: bool) -> Self {
|
||||
Self {
|
||||
|
@ -46,7 +57,7 @@ impl Graph {
|
|||
}
|
||||
|
||||
pub fn print_graph(&self) {
|
||||
for i in 0..self.nvertices as usize {
|
||||
for i in 0..self.nvertices {
|
||||
print!("{} -->", i);
|
||||
let mut p_opt = self.edges[i].clone();
|
||||
while let Some(p) = p_opt {
|
||||
|
@ -77,4 +88,40 @@ impl Graph {
|
|||
self.insert_edge(x.try_into().unwrap(), y, directed);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bfs(&self, start: usize) {
|
||||
let mut state = BfsState::new();
|
||||
let mut q: VecDeque<usize> = VecDeque::new();
|
||||
q.push_back(start);
|
||||
state.discovered[start] = true;
|
||||
|
||||
while let Some(v) = q.pop_front() {
|
||||
println!("process_vertex_early: {:?}", v);
|
||||
state.processed[v] = true;
|
||||
let mut p_opt = &self.edges[v];
|
||||
while let Some(p) = p_opt {
|
||||
let y: usize = p.y.try_into().unwrap();
|
||||
if !state.processed[y] || self.directed {
|
||||
println!("process edge ({:?},{:?})", v, y);
|
||||
}
|
||||
if !state.discovered[y] {
|
||||
q.push_back(y);
|
||||
state.discovered[y] = true;
|
||||
state.parent[y] = v.try_into().unwrap();
|
||||
}
|
||||
p_opt = &p.next;
|
||||
}
|
||||
println!("procesess vertex late: {:?}", v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BfsState {
|
||||
pub fn new() -> Self {
|
||||
BfsState {
|
||||
discovered: vec![false; MAXV],
|
||||
processed: vec![false; MAXV],
|
||||
parent: vec![-1; MAXV],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -21,4 +21,6 @@ fn main() {
|
|||
5 2";
|
||||
graph.read_graph(data.to_string());
|
||||
graph.print_graph();
|
||||
|
||||
graph.bfs(1);
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue