0
0
DSA Typescriptprogramming~10 mins

BFS Breadth First Search on Graph in DSA Typescript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to initialize the queue with the start node.

DSA Typescript
const queue: number[] = [[1]];
Drag options to blanks, or click blank then click option'
Agraph
B0
CstartNode
Dvisited
Attempts:
3 left
💡 Hint
Common Mistakes
Adding the whole graph or visited set instead of the start node.
Starting with an empty queue.
2fill in blank
medium

Complete the code to mark the current node as visited.

DSA Typescript
visited[[1]] = true;
Drag options to blanks, or click blank then click option'
Agraph
Bqueue
CstartNode
Dnode
Attempts:
3 left
💡 Hint
Common Mistakes
Marking the queue or graph as visited instead of the node.
Not marking nodes as visited, causing infinite loops.
3fill in blank
hard

Fix the error in the loop that processes neighbors of the current node.

DSA Typescript
for (const neighbor of graph[[1]]) {
Drag options to blanks, or click blank then click option'
Anode
Bqueue
Cvisited
DstartNode
Attempts:
3 left
💡 Hint
Common Mistakes
Using queue or visited as index causes errors or wrong neighbors.
Using startNode instead of current node inside the loop.
4fill in blank
hard

Fill both blanks to check if a neighbor is unvisited and add it to the queue.

DSA Typescript
if (!visited[[1]]) {
  queue.[2](neighbor);
}
Drag options to blanks, or click blank then click option'
Aneighbor
Bpush
Cpop
Dnode
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push adds/removes wrong elements.
Checking visited status of wrong variable.
5fill in blank
hard

Fill all three blanks to complete the BFS function that returns the order of visited nodes.

DSA Typescript
function bfs(graph: number[][], startNode: number): number[] {
  const visited: boolean[] = new Array(graph.length).fill(false);
  const queue: number[] = [startNode];
  const order: number[] = [];

  while (queue.length > 0) {
    const [1] = queue.shift()!;
    if (!visited[[2]]) {
      visited[[3]] = true;
      order.push(node);

      for (const neighbor of graph[node]) {
        if (!visited[neighbor]) {
          queue.push(neighbor);
        }
      }
    }
  }
  return order;
}
Drag options to blanks, or click blank then click option'
Anode
BstartNode
Dqueue
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently causes errors.
Not marking nodes as visited before processing neighbors.