Data Structure BFS Practice Questions with Solutions

Introductions

Breadth-First Search (BFS) is a graph traversal technique that visits vertices level by level. It starts from a selected vertex and first visits all its immediate neighbors before moving to the next level. BFS commonly uses a Queue to manage the vertices that need to be processed. In this chapter, you will practice BFS through 10 solved JavaScript questions covering traversal, levels, distances, paths, and practical graph problems. Data Structure BFS practice questions with solutions help to understand the concepts.

Question 1: Perform BFS Traversal from a Starting Vertex

Question

Given the following graph:

const graph = {
  A: ["B", "C"],
  B: ["D"],
  C: ["E"],
  D: [],
  E: []
};

Perform BFS starting from vertex A.

Solution

BFS uses a queue.

const graph = {
  A: ["B", "C"],
  B: ["D"],
  C: ["E"],
  D: [],
  E: []
};

function bfs(graph, start) {
  const queue = [start];
  const visited = new Set();
  const result = [];

  visited.add(start);

  while (queue.length > 0) {
    const vertex = queue.shift();

    result.push(vertex);

    for (const neighbor of graph[vertex]) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor);
      }
    }
  }

  return result;
}

console.log(bfs(graph, "A"));

Output

[ 'A', 'B', 'C', 'D', 'E' ]

Answer

The BFS traversal starting from A is:

A → B → C → D → E

BFS visits vertices level by level.


Question 2: Implement BFS Using a Custom Queue

Question

Instead of using shift(), create a simple queue using an index and perform BFS.

const graph = {
  1: [2, 3],
  2: [4],
  3: [5],
  4: [],
  5: []
};

Solution

const graph = {
  1: [2, 3],
  2: [4],
  3: [5],
  4: [],
  5: []
};

function bfs(graph, start) {
  const queue = [start];
  let front = 0;

  const visited = new Set();
  const result = [];

  visited.add(start);

  while (front < queue.length) {
    const vertex = queue[front++];

    result.push(vertex);

    for (const neighbor of graph[vertex]) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor);
      }
    }
  }

  return result;
}

console.log(bfs(graph, 1));

Output

[ 1, 2, 3, 4, 5 ]

Answer

The front variable acts like the front pointer of a queue, allowing BFS to process elements without repeatedly removing items from the beginning of the array.


Question 3: Find the BFS Level of Every Vertex

Question

Given:

const graph = {
  A: ["B", "C"],
  B: ["D", "E"],
  C: ["F"],
  D: [],
  E: [],
  F: []
};

Find the level of every vertex when BFS starts from A.

Solution

The starting vertex has level 0.

const graph = {
  A: ["B", "C"],
  B: ["D", "E"],
  C: ["F"],
  D: [],
  E: [],
  F: []
};

function bfsLevels(graph, start) {
  const queue = [start];
  const level = {
    [start]: 0
  };

  let front = 0;

  while (front < queue.length) {
    const vertex = queue[front++];

    for (const neighbor of graph[vertex]) {
      if (!(neighbor in level)) {
        level[neighbor] = level[vertex] + 1;
        queue.push(neighbor);
      }
    }
  }

  return level;
}

console.log(bfsLevels(graph, "A"));

Output

{
  A: 0,
  B: 1,
  C: 1,
  D: 2,
  E: 2,
  F: 2
}

Answer

The BFS levels are:

Level 0 → A
Level 1 → B, C
Level 2 → D, E, F


Question 4: Find the Shortest Distance Between Two Vertices

Question

Use BFS to find the shortest distance from A to F.

const graph = {
  A: ["B", "C"],
  B: ["D"],
  C: ["E"],
  D: ["F"],
  E: ["F"],
  F: []
};

Solution

BFS can find the shortest distance in an unweighted graph.

const graph = {
  A: ["B", "C"],
  B: ["D"],
  C: ["E"],
  D: ["F"],
  E: ["F"],
  F: []
};

function shortestDistance(graph, start, target) {
  const queue = [start];
  const distance = {
    [start]: 0
  };

  let front = 0;

  while (front < queue.length) {
    const vertex = queue[front++];

    if (vertex === target) {
      return distance[vertex];
    }

    for (const neighbor of graph[vertex]) {
      if (!(neighbor in distance)) {
        distance[neighbor] = distance[vertex] + 1;
        queue.push(neighbor);
      }
    }
  }

  return -1;
}

console.log(shortestDistance(graph, "A", "F"));

Output

2

Answer

The shortest distance from A to F is 2 edges.

One shortest route is:

A → B → D → F

Wait: that route contains 3 edges, while:

A → C → E → F

also contains 3 edges.

Therefore, the correct shortest distance is:

3

The corrected output is:

3

Question 5: Find the Shortest Path Using BFS

Question

Find the actual shortest path from A to F.

const graph = {
  A: ["B", "C"],
  B: ["D"],
  C: ["E"],
  D: ["F"],
  E: ["F"],
  F: []
};

Solution

Store the parent of every visited vertex.

const graph = {
  A: ["B", "C"],
  B: ["D"],
  C: ["E"],
  D: ["F"],
  E: ["F"],
  F: []
};

function shortestPath(graph, start, target) {
  const queue = [start];
  const parent = {
    [start]: null
  };

  let front = 0;

  while (front < queue.length) {
    const vertex = queue[front++];

    if (vertex === target) {
      break;
    }

    for (const neighbor of graph[vertex]) {
      if (!(neighbor in parent)) {
        parent[neighbor] = vertex;
        queue.push(neighbor);
      }
    }
  }

  if (!(target in parent)) {
    return [];
  }

  const path = [];
  let current = target;

  while (current !== null) {
    path.push(current);
    current = parent[current];
  }

  return path.reverse();
}

console.log(shortestPath(graph, "A", "F"));

Output

[ 'A', 'B', 'D', 'F' ]

Answer

The shortest path found by BFS is:

A → B → D → F

It contains 3 edges.


Question 6: Count the Number of Vertices Visited by BFS

Question

Given this graph, count how many vertices BFS visits when starting from A.

const graph = {
  A: ["B", "C"],
  B: ["D"],
  C: [],
  D: ["E"],
  E: []
};

Solution

const graph = {
  A: ["B", "C"],
  B: ["D"],
  C: [],
  D: ["E"],
  E: []
};

function countVisited(graph, start) {
  const queue = [start];
  const visited = new Set([start]);

  let front = 0;

  while (front < queue.length) {
    const vertex = queue[front++];

    for (const neighbor of graph[vertex]) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor);
      }
    }
  }

  return visited.size;
}

console.log(countVisited(graph, "A"));

Output

5

Answer

BFS visits all five vertices:

A, B, C, D, E

Therefore, the answer is 5.


Question 7: Stop BFS When a Target Vertex Is Found

Question

Perform BFS starting from A and stop as soon as vertex E is found.

const graph = {
  A: ["B", "C"],
  B: ["D"],
  C: ["E"],
  D: ["F"],
  E: [],
  F: []
};

Solution

const graph = {
  A: ["B", "C"],
  B: ["D"],
  C: ["E"],
  D: ["F"],
  E: [],
  F: []
};

function searchBFS(graph, start, target) {
  const queue = [start];
  const visited = new Set([start]);

  let front = 0;

  while (front < queue.length) {
    const vertex = queue[front++];

    if (vertex === target) {
      return `Found ${target}`;
    }

    for (const neighbor of graph[vertex]) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor);
      }
    }
  }

  return `${target} not found`;
}

console.log(searchBFS(graph, "A", "E"));

Output

Found E

Answer

BFS reaches E through:

A → C → E

Once E is removed from the queue and processed, the search stops.


Question 8: Find All Vertices at a Specific BFS Level

Question

Using BFS, find all vertices at level 2 from vertex A.

const graph = {
  A: ["B", "C"],
  B: ["D", "E"],
  C: ["F"],
  D: [],
  E: [],
  F: []
};

Solution

const graph = {
  A: ["B", "C"],
  B: ["D", "E"],
  C: ["F"],
  D: [],
  E: [],
  F: []
};

function verticesAtLevel(graph, start, targetLevel) {
  const queue = [start];
  const level = {
    [start]: 0
  };

  const result = [];

  let front = 0;

  while (front < queue.length) {
    const vertex = queue[front++];

    if (level[vertex] === targetLevel) {
      result.push(vertex);
    }

    for (const neighbor of graph[vertex]) {
      if (!(neighbor in level)) {
        level[neighbor] = level[vertex] + 1;
        queue.push(neighbor);
      }
    }
  }

  return result;
}

console.log(verticesAtLevel(graph, "A", 2));

Output

[ 'D', 'E', 'F' ]

Answer

The vertices at BFS level 2 are:

D, E, F


Question 9: Check Whether a Vertex Is Reachable Using BFS

Question

Use BFS to determine whether vertex F can be reached from A.

const graph = {
  A: ["B"],
  B: ["C"],
  C: [],
  D: ["E"],
  E: ["F"],
  F: []
};

Solution

const graph = {
  A: ["B"],
  B: ["C"],
  C: [],
  D: ["E"],
  E: ["F"],
  F: []
};

function isReachable(graph, start, target) {
  const queue = [start];
  const visited = new Set([start]);

  let front = 0;

  while (front < queue.length) {
    const vertex = queue[front++];

    if (vertex === target) {
      return true;
    }

    for (const neighbor of graph[vertex]) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor);
      }
    }
  }

  return false;
}

console.log(isReachable(graph, "A", "F"));

Output

false

Answer

F is not reachable from A.

From A, BFS can visit:

A → B → C

But D → E → F is a separate part of the graph.


Question 10: Perform BFS on a Grid

Question

Consider this grid:

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

Starting from (0, 0), use BFS to count how many cells containing 0 can be reached.

You can move up, down, left, or right.

Solution

const grid = [
  [0, 0, 1],
  [1, 0, 1],
  [0, 0, 0]
];

function bfsGrid(grid, startRow, startCol) {
  const rows = grid.length;
  const cols = grid[0].length;

  const queue = [[startRow, startCol]];
  const visited = new Set();

  const directions = [
    [-1, 0],
    [1, 0],
    [0, -1],
    [0, 1]
  ];

  visited.add(`${startRow},${startCol}`);

  let front = 0;

  while (front < queue.length) {
    const [row, col] = queue[front++];

    for (const [dr, dc] of directions) {
      const newRow = row + dr;
      const newCol = col + dc;

      if (
        newRow >= 0 &&
        newRow < rows &&
        newCol >= 0 &&
        newCol < cols &&
        grid[newRow][newCol] === 0 &&
        !visited.has(`${newRow},${newCol}`)
      ) {
        visited.add(`${newRow},${newCol}`);
        queue.push([newRow, newCol]);
      }
    }
  }

  return visited.size;
}

console.log(bfsGrid(grid, 0, 0));

Output

6

Answer

Starting from (0, 0), BFS can reach all six cells containing 0.

The BFS explores the grid level by level, just like it explores vertices in a graph.

Key Takeaways

  • BFS stands for Breadth-First Search.
  • BFS explores a graph level by level.
  • BFS commonly uses a Queue.
  • A visited structure prevents processing the same vertex repeatedly.
  • BFS can calculate the level of each reachable vertex.
  • BFS can find the shortest path in an unweighted graph.
  • BFS can reconstruct the actual shortest path using parent information.
  • BFS can stop early when a target vertex is found.
  • BFS can be applied to grids and matrix-based problems.
  • The basic BFS pattern is: Queue → Visit → Process Neighbors → Add Unvisited Neighbors.

FAQs

1. What is BFS in data structures?

BFS, or Breadth-First Search, is a graph traversal algorithm that visits vertices level by level from a starting vertex.

2. Which data structure is used by BFS?

BFS uses a Queue because vertices are processed in the order in which they are discovered.

3. Why do we use a visited set in BFS?

The visited set prevents BFS from processing the same vertex multiple times, especially when the graph contains cycles.

4. Can BFS find the shortest path?

Yes. BFS can find the shortest path in an unweighted graph, where each edge has equal cost.

5. What is the starting vertex’s BFS level?

The starting vertex is normally assigned level 0.

6. Can BFS be used on a grid?

Yes. A grid can be treated as a graph where each cell is a vertex and valid neighboring cells are connected.

7. What is the main difference between BFS and DFS?

BFS explores vertices level by level using a queue, while DFS explores as deeply as possible before backtracking, commonly using recursion or a stack.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top