MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / dfs

Function dfs

publication/code/chapter09/dfs.rs:86–126  ·  view source on GitHub ↗
(graph: Vec<(Graph, usize)>)

Source from the content-addressed store, hash-verified

84}
85
86fn dfs(graph: Vec<(Graph, usize)>) {
87 let mut gp = graph;
88 let mut nodes: Vec<usize> = Vec::new();
89 let mut temp: Vec<usize> = Vec::new();
90
91 gp[1].1 = 1;
92 let mut curr = gp[1].0.get_first().clone();
93
94 // 打印图
95 print!("{}->",1);
96 while let Some(val) = curr {
97 nodes.insert(0, val.borrow().data);
98 curr = val.borrow().next.clone();
99 }
100
101 // 打印深度优先图
102 loop{
103 if 0 == nodes.len() {
104 break;
105 }else{
106 let data = nodes.pop().unwrap();
107 if 0 == gp[data].1 { // 未被访问过
108 // 更改访问状态为已访问过
109 gp[data].1 = 1;
110 print!("{data}->");
111
112 // 节点加入 temp,并对其进行深度优先搜索
113 let mut curr = gp[data].0.get_first().clone();
114 while let Some(val) = curr {
115 temp.push(val.borrow().data);
116 curr = val.borrow().next.clone();
117 }
118
119 while !temp.is_empty(){
120 nodes.push(temp.pop().unwrap());
121 }
122 }
123 }
124 }
125 println!("");
126}
127
128fn main() {
129 let data = [

Callers 1

mainFunction · 0.70

Calls 6

get_firstMethod · 0.45
insertMethod · 0.45
lenMethod · 0.45
popMethod · 0.45
pushMethod · 0.45
is_emptyMethod · 0.45

Tested by

no test coverage detected