0%

230421-图-广度优先

给一个单向关系图,实现广度优先算法

题解

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
use std::collections::HashMap;
use std::collections::HashSet;

fn search_m<'a>(hashmap: HashMap<&str, Vec<&'a str>>) -> Option<&'a str> {
let mut queue: Vec<&str> = Vec::new();
let mut check_list = HashSet::new();
if let Some(first) = hashmap.get("you") {
for ele in first {
queue.push(ele);
}
}
while queue.len() > 0 {
let c = queue.remove(0);
if check_list.contains(c) {
continue;
}
check_list.insert(c);
if c.ends_with("m") {
return Some(c);
}
if let Some(eles) = hashmap.get(c) {
for ele in eles {
queue.push(ele)
}
}
}
None
}

fn main() {
let mut hashmap = HashMap::new();
hashmap.insert("you", vec!["alice", "bob", "claire"]);
hashmap.insert("bob", vec!["anuj", "peggy"]);
hashmap.insert("alice", vec!["peggy"]);
hashmap.insert("claire", vec!["you", "thom", "jonny"]);
hashmap.insert("anuj", vec![]);
hashmap.insert("peggy", vec![]);
hashmap.insert("thom", vec![]);
hashmap.insert("jonny", vec![]);

let v = search_m(hashmap);
match v {
Some(i) => {
println!("find mongoose! name {:?}", i);
}
None => {
println!("not find mongoose");
}
}
}

思路

创建一个队列,把离自己最近的一层放在队列内
队列出队,检查当前元素是否符合要求,符合终止查找
不符合,把该元素的子集放入队列
这样子,只要队列不为空,就能把所有的内容检查一遍,且依照离原点最近的距离检查。