BFS Graph Implementation JS
bfs of a graph in js
Here’s how you can implement Breadth-First Search (BFS) of a graph in JavaScript using an
adjacency list:
✅ BFS Implementation in JavaScript
javascript
function bfs(graph, startNode) {
let visited = new Set(); // Track visited nodes
let queue = [startNode]; // Initialize queue with start node
let result = []; // Store the BFS traversal
while ([Link] > 0) {
const node = [Link](); // Dequeue from the front
if () {
[Link](node); // Mark node as visited
[Link](node); // Add to result
// Enqueue all unvisited neighbors
for (const neighbor of graph[node]) {
if () {
[Link](neighbor);
}
}
}
}
return result;
}
🧪 Example Usage
javascript
const graph = {
A: ['B', 'C'],
B: ['D', 'E'],
1/2
C: ['F'],
D: [],
E: ['F'],
F: []
};
[Link](bfs(graph, 'A')); // Output: ['A', 'B', 'C', 'D', 'E', 'F']
🔍 Explanation
graph: An object where each key is a node and the value is an array of its neighbors.
startNode: The node where BFS starts.
visited: Ensures nodes are not processed multiple times.
queue: Stores the next node to explore in FIFO order.
Would you like a version that works on undirected or weighted graphs as well?
Do you like this personality?
2/2