0
0
DSA Typescriptprogramming~3 mins

Why BFS Breadth First Search on Graph in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

What if you could explore a huge maze without ever getting lost or wasting time on dead ends?

The Scenario

Imagine you are in a huge maze and want to find the shortest path to the exit. You try to explore every path by yourself, going deep into one path before checking others.

This can be confusing and you might get lost or take a very long time to find the exit.

The Problem

Manually exploring each path deeply means you might waste time going down long dead ends first.

You can forget where you came from or miss shorter paths nearby.

This approach is slow and error-prone when the maze or network is big.

The Solution

BFS (Breadth First Search) helps by exploring all paths one step at a time, level by level.

It uses a queue to remember which places to visit next, ensuring you find the shortest path quickly and without confusion.

Before vs After
Before
function exploreMaze(start) {
  // Go deep first, might get lost
  if (start is exit) return;
  for each neighbor {
    exploreMaze(neighbor);
  }
}
After
function bfs(start) {
  let queue = [start];
  while (queue.length > 0) {
    let current = queue.shift();
    visit(current);
    add unvisited neighbors to queue;
  }
}
What It Enables

BFS enables you to find the shortest path or explore all connected points efficiently and clearly.

Real Life Example

Social networks use BFS to find friends of friends or suggest connections by exploring nearby people step by step.

Key Takeaways

BFS explores neighbors level by level using a queue.

It finds shortest paths in unweighted graphs.

It avoids getting lost by visiting nodes in order of distance.