Breadth First Search: Shortest Reach

  • + 0 comments

    Here's a PHP solution for the "Breadth First Search: Shortest Reach" problem on HackerRank. This implementation uses a BFS algorithm to find the shortest path in an unweighted graph.

    <?php
    function bfs($n, $m, $edges, $s) {
        // Initialize the graph
        $graph = array_fill(1, $n, []);
        foreach ($edges as $edge) {
            list($u, $v) = $edge;
            $graph[$u][] = $v;
            $graph[$v][] = $u;
        }
    
        // Initialize distances
        $distances = array_fill(1, $n, -1);
        $distances[$s] = 0;
    
        // BFS using a queue
        $queue = new SplQueue();
        $queue->enqueue($s);
    
        while (!$queue->isEmpty()) {
            $node = $queue->dequeue();
            foreach ($graph[$node] as $neighbor) {
                if ($distances[$neighbor] == -1) {
                    $distances[$neighbor] = $distances[$node] + 6;
                    $queue->enqueue($neighbor);
                }
            }
        }
    
        // Exclude the start node distance
        $result = [];
        foreach ($distances as $key => $distance) {
            if ($key != $s) {
                $result[] = $distance;
            }
        }
    
        return $result;
    }
    ?>
    

    Explanation

    1. Graph Initialization:

      • The graph is initialized as an adjacency list. Each node points to a list of its neighbors.
    2. Distance Initialization:

      • A distances array is initialized to store the shortest distance from the start node s to each node. It is initially set to -1 for all nodes to indicate they are unvisited, and 0 for the start node.
    3. BFS Implementation:

      • A queue is used to explore the graph level by level. The start node is enqueued first. For each node dequeued, its unvisited neighbors are enqueued, and their distances are updated.
    4. Result Preparation:

      • The distances for all nodes except the start node are prepared for output.
    5. Input Handling:

      • The input is read, and the BFS function is called for each test case. The results are then printed.

    This solution reads input directly from php://stdin and is designed to be run in a competitive programming environment where inputs are provided in a specific format. For testing locally, you might need to modify the input handling part to use hardcoded values or read from a file.