- Typescript Daily
- Posts
- Discovering BFS in TypeScript: Traverse Graphs with Precision!
Discovering BFS in TypeScript: Traverse Graphs with Precision!
Unravel the power of Breadth-First Search (BFS) in TypeScript! Explore efficient graph traversal and unlock new pathways in your coding journey.
Dear TypeScript Enthusiasts,
Diving into the depths of algorithms opens doors to fascinating techniques like Breadth-First Search (BFS). Mastering BFS is not just about traversal; it's about unveiling the power of exploring data structures systematically and efficiently.
Understanding Breadth-First Search (BFS)
BFS operates by systematically exploring all the vertices of a graph or nodes of a tree in layers, starting from the root or a specified node. It visits all neighbors of the starting node before moving on to their respective neighbors, ensuring exploration in layers.
Embracing BFS in TypeScript
class Graph {
vertices: number;
adjacencyList: Map<number, number[]>;
constructor(vertices: number) {
this.vertices = vertices;
this.adjacencyList = new Map();
for (let i = 0; i < vertices; i++) {
this.adjacencyList.set(i, []);
}
}
addEdge(source: number, destination: number) {
this.adjacencyList.get(source)?.push(destination);
this.adjacencyList.get(destination)?.push(source);
}
bfs(startingNode: number): number[] {
const visited: boolean[] = [];
const result: number[] = [];
const queue: number[] = [];
for (let i = 0; i < this.vertices; i++) {
visited[i] = false;
}
visited[startingNode] = true;
queue.push(startingNode);
while (queue.length) {
const current = queue.shift()!;
result.push(current);
const neighbors = this.adjacencyList.get(current);
if (neighbors) {
for (const neighbor of neighbors) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.push(neighbor);
}
}
}
}
return result;
}
}
// Example Usage:
const graph = new Graph(6);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 4);
graph.addEdge(3, 5);
graph.addEdge(4, 5);
console.log("BFS Traversal:", graph.bfs(0)); // Output: [0, 1, 2, 3, 4, 5]
Real-World Applications
BFS finds its application in numerous domains, from network broadcasting in computer networks to shortest path algorithms in GPS navigation systems. Its ability to systematically explore makes it indispensable in various scenarios.
Companies Seeking BFS Expertise
Leading tech companies like Facebook, Microsoft, and Amazon often assess BFS knowledge in their frontend engineering interviews. Mastery of BFS demonstrates problem-solving skills and a strong understanding of graph algorithms.
Explore BFS in TypeScript, unravel the layers, and witness its prowess in navigating through graphs and trees efficiently!
Happy Exploring!
Reply