The Signal Cascade (BFS)

MediumAcc. 91.4%
+35 XP 15

The Signal Propagation (BFS)

Breadth-First Search (BFS) is like a signal ripple. Starting from a source, the signal moves outward level by level, reaching all direct neighbors before moving to their neighbors. It is the perfect tool for finding the "shortest distance" in a network where every hop costs the same.

The Assignment

Your mission is to propagate the signal across the network. Your function receives an adjacencyList and a startNode.

  1. Use a Queue to track the frontier of nodes the signal is reaching.
  2. Maintain a Visited Set to ensure you don't circle back to the same node twice.
  3. While the queue is not empty:
    • Dequeue the current node.
    • Print the node's identifier.
    • Enqueue all of its neighbors that have not been visited yet.

01EXAMPLE 1

Inputadj=[[0,1,1],[1,0,0],[1,0,0]]
Output0 1 2

Explanation: Explore 0, then its neighbors 1 and 2.

Constraints

  • Ignore self-loops and handle disconnected components if necessary.
GraphsAlgorithms
JavaScript
Loading...
1 Hidden

Input Arguments

adj[[0,1,1],[1,0,0],[1,0,0]]

Expected Output

0
1
2

Click RUN to test your solution