Perl Program to Implement Breadth-First Search (BFS)

Perl Program to Implement Breadth-First Search (BFS)

Breadth-First Search, commonly known as BFS, is one of the most important algorithms for exploring graphs and trees. Unlike Depth-First Search (DFS), which dives deep into one path before backtracking, BFS explores all nodes level by level. This systematic approach makes it ideal for finding the shortest path between nodes, solving puzzles, and analyzing networks. For beginners, BFS is a great way to understand queues, graph traversal, and algorithmic thinking in a practical, hands-on way.

BFS is widely used in real-life scenarios, such as social network analysis, web crawlers, shortest path problems, and even AI pathfinding in games. Learning BFS in Perl allows beginners to see how structured traversal works, how to manage a queue to control the order of exploration, and how to prevent revisiting nodes. By practicing BFS, beginners gain a solid foundation for understanding more advanced graph algorithms and problem-solving techniques.

Program 1: BFS Using a Queue on a Graph

This program demonstrates a simple BFS traversal using a queue on a graph represented with a hash.

use strict;
use warnings;

my %graph = (
    A => ['B', 'C'],
    B => ['D', 'E'],
    C => ['F'],
    D => [],
    E => ['F'],
    F => []
);

my %visited;
my @queue = ('A');

print "BFS starting from node A: ";
while (@queue) {

    my $node = shift @queue;
    next if $visited{$node};

    print "$node ";
    $visited{$node} = 1;

    push @queue, @{$graph{$node}};

}

print "\n";

In this example, BFS starts at node ‘A’ and explores neighbors level by level. Using a queue ensures nodes are visited in the correct order. Beginners can see the importance of keeping track of visited nodes to prevent infinite loops and understand how BFS systematically explores a graph.

Program 2: BFS Using a Queue and Array for Numeric Nodes

Graphs aren’t always labeled with letters. This program demonstrates BFS with numeric nodes, which could include zero or negative numbers.

use strict;
use warnings;

my %graph = (
    -1 => [0, 1],
    0 => [-2, 2],
    1 => [3],
    -2 => [],
    2 => [],
    3 => []
);

my %visited;
my @queue = (-1);

print "BFS on numeric graph starting from -1: ";
while (@queue) {

    my $node = shift @queue;
    next if $visited{$node};

    print "$node ";
    $visited{$node} = 1;

    push @queue, @{$graph{$node}};

}

print "\n";

This shows that BFS works with any type of node labels. Beginners learn that the algorithm is flexible and depends more on structure than on the specific type of identifiers.

Program 3: BFS on a Graph Represented by an Adjacency Matrix

Sometimes graphs are represented by adjacency matrices rather than hashes. This program demonstrates BFS in that context.

use strict;
use warnings;

my @graph = (
    [0, 1, 1, 0, 0, 0],
    [0, 0, 0, 1, 1, 0],
    [0, 0, 0, 0, 0, 1],
    [0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 1],
    [0, 0, 0, 0, 0, 0]
);

my @visited;
my @queue = (0);

print "BFS on graph with adjacency matrix: ";
while (@queue) {

    my $node = shift @queue;
    next if $visited[$node];

    print "$node ";
    $visited[$node] = 1;

    for my $i (0..$#{$graph[0]}) {
        push @queue, $i if $graph[$node][$i] && !$visited[$i];
    }

}

print "\n";

This program shows beginners that BFS can work regardless of graph representation. Whether using a hash or a matrix, BFS’s core idea of level-by-level exploration remains unchanged.

Program 4: BFS to Find Shortest Path Between Two Nodes

One of BFS’s key strengths is finding the shortest path. This program demonstrates BFS to determine the shortest path between two nodes.

use strict;
use warnings;

my %graph = (
    A => ['B', 'C'],
    B => ['D', 'E'],
    C => ['F'],
    D => [],
    E => ['F'],
    F => []
);

sub bfs_shortest_path {

    my ($start, $end) = @_;
    my %visited = ($start => 1);
    my @queue = ([$start]);

    while (@queue) {

        my $path = shift @queue;
        my $node = $path->[-1];

        return $path if $node eq $end;

        foreach my $neighbor (@{$graph{$node}}) {
            next if $visited{$neighbor};
            $visited{$neighbor} = 1;
            push @queue, [@$path, $neighbor];
        }

    }

    return;

}

my $path = bfs_shortest_path('A', 'F');
print "Shortest path from A to F: ", join(" -> ", @$path), "\n";

This program shows beginners a practical use of BFS beyond traversal. By storing paths in the queue, BFS naturally finds the shortest path, which is a common application in networking, maps, and AI.

Program 5: BFS on Disconnected Graphs

Sometimes graphs have multiple disconnected components. This example ensures BFS visits every node.

use strict;
use warnings;

my %graph = (
    A => ['B'],
    B => [],
    C => ['D'],
    D => []
);

my %visited;

sub bfs_disconnected {

    foreach my $node (keys %graph) {

        next if $visited{$node};
        my @queue = ($node);

        while (@queue) {

            my $current = shift @queue;
            next if $visited{$current};

            print "$current ";
            $visited{$current} = 1;

            push @queue, @{$graph{$current}};

        }

    }

}

print "BFS on disconnected graph: ";
bfs_disconnected();
print "\n";

This example teaches beginners that BFS can handle complex graphs with multiple components. Running BFS for every unvisited node ensures complete coverage.

Frequently Asked Questions (FAQ)

BFS raises several common questions for new learners exploring graph algorithms.

Q1. What is the time complexity of BFS?
BFS runs in O(V + E), where V is the number of vertices and E is the number of edges.

Q2. How does BFS differ from DFS?
BFS explores nodes level by level, while DFS goes deep into one branch before backtracking. BFS is ideal for shortest paths, DFS for deep exploration.

Q3. Can BFS handle negative node labels?
Yes, node labels can be letters, numbers, or even negative values, as long as the graph structure is clear.

Q4. Does BFS work on disconnected graphs?
Yes, by starting BFS on each unvisited component, you can traverse the entire graph.

Q5. When is BFS more useful than DFS?
BFS is preferred when you need the shortest path or want to explore all neighbors evenly. DFS is better for exhaustive searches or solving puzzles.

Conclusion

Breadth-First Search is a powerful algorithm for exploring graphs systematically. By learning BFS in Perl, beginners can grasp key programming concepts like queues, graph representation, and level-by-level traversal. BFS is especially useful for shortest path problems, network analysis, and practical applications in computing.

Practicing BFS helps beginners build confidence in graph algorithms and problem-solving techniques. By trying different graph structures, disconnected components, and numeric or negative labels, learners gain flexibility and understanding. With BFS in their toolkit, beginners are ready to tackle more advanced graph algorithms and real-world programming challenges.

Scroll to Top