-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathgraph-unweighted-bfs.rs
More file actions
63 lines (54 loc) · 1.95 KB
/
Copy pathgraph-unweighted-bfs.rs
File metadata and controls
63 lines (54 loc) · 1.95 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
/// Example demonstrating how to use pathfinding with unweighted graphs using BFS.
/// In unweighted graphs, the successor function returns just nodes without costs.
use pathfinding::prelude::bfs;
use std::collections::HashMap;
fn main() {
// Define an unweighted graph as an adjacency list
// Each node maps to a list of neighbors (no weights)
let graph: HashMap<&str, Vec<&str>> = [
("A", vec!["B", "C"]),
("B", vec!["A", "D", "E"]),
("C", vec!["A", "F"]),
("D", vec!["B"]),
("E", vec!["B", "F"]),
("F", vec!["C", "E"]),
]
.iter()
.cloned()
.collect();
// Successor function returns just neighbors (no costs)
let successors = |node: &&str| -> Vec<&str> { graph.get(node).cloned().unwrap_or_default() };
// Find shortest path from A to F using BFS
let result = bfs(&"A", successors, |&node| node == "F");
match result {
Some(path) => {
println!("Shortest path from A to F: {path:?}");
println!("Number of hops: {}", path.len() - 1);
assert_eq!(path, vec!["A", "C", "F"]);
assert_eq!(path.len() - 1, 2); // 2 hops
}
None => println!("No path found"),
}
// Example 2: Find path from A to E
let result2 = bfs(&"A", successors, |&node| node == "E");
match result2 {
Some(path) => {
println!("\nShortest path from A to E: {path:?}");
println!("Number of hops: {}", path.len() - 1);
}
None => println!("No path found"),
}
println!("\nExample completed successfully!");
println!("\nThis demonstrates BFS on an unweighted graph where:");
println!("- All edges have equal cost (1 hop)");
println!("- Successor function returns just nodes, not (node, cost) pairs");
println!("- BFS finds the path with the fewest hops");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_unweighted_bfs_example() {
main();
}
}