Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Medium · Free

Explain BFS on a graph — queue, visited set, use cases.

FresherFundamentalsData Structures & Algorithms
Model answer

BFS on graphs

Explore layer by layer with a queue and visited set—shortest path in unweighted graphs.

java
void bfs(int start, Map<Integer, List<Integer>> g) {
  Queue<Integer> q = new ArrayDeque<>();
  Set<Integer> vis = new HashSet<>();
  q.add(start); vis.add(start);
  while (!q.isEmpty()) {
    int u = q.remove();
    for (int v : g.getOrDefault(u, List.of())) {
      if (vis.add(v)) q.add(v);
    }
  }
}
Use cases: social friend distance, maze shortest steps, broadcast routing.