Perl Graph BFS for Shortest Path in Unweighted Graph
sub find_shortest_path_bfs { my ($graph, $start_node, $end_node) = @_; # Check for invalid input: empty graph, start/end nodes not in graph return undef unless $graph && ref($graph) eq 'HASH'; return undef unless exists $graph->{$start_node} && exists $graph->{$end_node}; return...
This Perl script implements the Breadth-First Search (BFS) algorithm to find the shortest path between two nodes in an unweighted graph. BFS systematically explores the graph layer by layer, guaranteeing that the first t...
The `find_shortest_path_bfs` function utilizes a queue to manage nodes to visit and a hash to keep track of visited nodes and their predecessors. It starts by enqueuing the `start_node` and marking it as visited. In each iteration, it dequeues a node, checks if it's the `end_node`, and if so, reconstructs the path using the `parent` hash. Otherwise, it iterates through the node's neighbors, enqueuing unvisited ones and updating their parent pointers. The `reconstruct_path` helper function backtracks from the `end_node` to the `start_node` using the `parent` map to build the path. The time complexity is O(V + E), where V is the number of vertices and E is the number of edges, because each vertex and edge is visited at most once. The space complexity is O(V) for the queue, visited set, and parent map. Edge cases handled include an empty graph, nodes not present in the graph, the start and end nodes being the same, and disconnected graphs where the target is unreachable.
function find_shortest_path_bfs(graph, start_node, end_node): if graph is empty or start/end nodes not in graph: return null if start_node equals end_node: return empty path initialize queue with start_node initialize vi...