What if you could always find the quickest way without guessing or getting lost?
Why Shortest Path in Unweighted Graph Using BFS in DSA Typescript?
Imagine you are in a city with many streets and intersections. You want to find the shortest way to walk from your home to a friend's house without knowing the map well.
If you try to guess the path by walking randomly or checking every street one by one, it will take a lot of time and effort.
Manually checking every possible path is slow and confusing. You might walk in circles or take longer routes without realizing it.
It is easy to get lost or waste time exploring paths that do not lead to your friend's house quickly.
Using the Breadth-First Search (BFS) method, you explore all nearby intersections first before moving further away.
This way, you find the shortest path step-by-step without missing any closer options.
BFS guarantees the shortest path in an unweighted graph because it checks all neighbors at the current distance before going deeper.
function findPath(graph, start, end) {
// Try all paths manually, very complex and slow
// No clear order of checking neighbors
}function bfsShortestPath(graph, start, end) {
const queue = [start];
const visited = new Set([start]);
const distance = new Map();
distance.set(start, 0);
while (queue.length) {
const node = queue.shift();
if (node === end) return distance.get(node);
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
distance.set(neighbor, distance.get(node) + 1);
queue.push(neighbor);
}
}
}
return -1;
}You can quickly find the shortest route in any network of connections without guessing or wasting time.
Finding the quickest way to send a message through a network of friends or computers where each connection has the same cost.
Manual path search is slow and error-prone.
BFS explores neighbors level by level to find the shortest path.
This method works best for unweighted graphs where all edges have equal cost.