Function breadth_first_search

Source
pub fn breadth_first_search<T: Eq + Hash + Clone>(
    graph: &Graph<T>,
    start: Rc<TreeNode<T>>,
) -> Vec<T>
Expand description

Performs a breadth-first search (BFS) on the given graph starting from the start node.

This function explores the graph level by level, visiting each node starting from the start node and moving outward to its neighbors. It returns the nodes in the order they were visited.

§Examples

use std::rc::Rc;
use dsa::data_structures::graph::Graph;
use dsa::data_structures::tree::TreeNode;
use dsa::algorithms::graph_traversal::breadth_first_search;

let mut graph = Graph::new();
let node1 = Rc::new(TreeNode::new(1));
let node2 = Rc::new(TreeNode::new(2));
let node3 = Rc::new(TreeNode::new(3));

graph.add_edge(Rc::clone(&node1), Rc::clone(&node2), Some(1));
graph.add_edge(Rc::clone(&node1), Rc::clone(&node3), Some(1));

let result = breadth_first_search(&graph, Rc::clone(&node1));
assert_eq!(result, vec![1, 2, 3]);

§Parameters

  • graph: A reference to the graph in which the search will take place.
  • start: The node from which the search begins.

§Returns

A vector containing the nodes in the order they were visited.