0% found this document useful (0 votes)
11 views2 pages

JavaScript BFS Graph Implementation

This document provides a JavaScript implementation of the Breadth-First Search (BFS) algorithm for traversing a graph using an adjacency list. It includes a function that tracks visited nodes, utilizes a queue for traversal, and demonstrates usage with an example graph. The BFS function returns the order of nodes visited starting from a specified node.

Uploaded by

ayush200992
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

JavaScript BFS Graph Implementation

This document provides a JavaScript implementation of the Breadth-First Search (BFS) algorithm for traversing a graph using an adjacency list. It includes a function that tracks visited nodes, utilizes a queue for traversal, and demonstrates usage with an example graph. The BFS function returns the order of nodes visited starting from a specified node.

Uploaded by

ayush200992
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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)) {
[Link](node); // Mark node as visited
[Link](node); // Add to result

// Enqueue all unvisited neighbors


for (const neighbor of graph[node]) {
if (![Link](neighbor)) {
[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

You might also like