| 84 | } |
| 85 | |
| 86 | fn 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 | |
| 128 | fn main() { |
| 129 | let data = [ |