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

Function bfs

publication/code/chapter09/bfs.rs:93–133  ·  view source on GitHub ↗
(graph: Vec<(Graph, usize)>)

Source from the content-addressed store, hash-verified

91}
92
93fn bfs(graph: Vec<(Graph, usize)>) {
94 let mut gp = graph;
95 let mut nodes = Vec::new();
96
97 gp[1].1 = 1;
98 let mut curr = gp[1].0.get_first().clone();
99
100 // 打印图
101 print!("{}->", 1);
102 while let Some(val) = curr {
103 nodes.push(val.borrow().data);
104 curr = val.borrow().next.clone();
105 }
106
107 // 打印广度优先图
108 loop {
109 if 0 == nodes.len() {
110 break;
111 } else {
112 // nodes 中首节点弹出,模仿了队列的特性
113 let data = nodes.remove(0);
114
115 // 节点未被访问过,加入 nodes, 修改其访问状态为 1
116 if 0 == gp[data].1 {
117 gp[data].1 = 1;
118
119 // 打印当前节点值
120 print!("{data}->");
121
122 // 将与当前节点相连的节点加入 nodes
123 let mut curr = gp[data].0.get_first().clone();
124 while let Some(val) = curr {
125 nodes.push(val.borrow().data);
126 curr = val.borrow().next.clone();
127 }
128 }
129 }
130 }
131
132 println!("");
133}
134
135fn main() {
136 let data = [

Callers 1

mainFunction · 0.70

Calls 4

get_firstMethod · 0.45
pushMethod · 0.45
lenMethod · 0.45
removeMethod · 0.45

Tested by

no test coverage detected