-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.js
More file actions
121 lines (97 loc) · 2.54 KB
/
bfs.js
File metadata and controls
121 lines (97 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// Graph represented as an adjacency list
class Graph {
constructor() {
this.adjacencyList = {};
}
addVertex(vertex) {
if (!this.adjacencyList[vertex]) {
this.adjacencyList[vertex] = [];
}
}
addEdge(v1, v2) {
this.adjacencyList[v1].push(v2);
this.adjacencyList[v2].push(v1); // Remove this line for directed graph
}
// BFS Implementation
bfs(start) {
const queue = [start];
const result = [];
const visited = {};
visited[start] = true;
while (queue.length) {
let vertex = queue.shift();
result.push(vertex);
this.adjacencyList[vertex].forEach(neighbor => {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.push(neighbor);
}
});
}
return result;
}
// BFS to find shortest path between two nodes
bfsShortestPath(start, end) {
const queue = [[start]];
const visited = new Set([start]);
while (queue.length) {
const path = queue.shift();
const vertex = path[path.length - 1];
if (vertex === end) {
return path;
}
for (let neighbor of this.adjacencyList[vertex]) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push([...path, neighbor]);
}
}
}
return null; // No path found
}
}
// Example usage
const graph = new Graph();
// Add vertices
['A', 'B', 'C', 'D', 'E', 'F'].forEach(v => graph.addVertex(v));
// Add edges
graph.addEdge('A', 'B');
graph.addEdge('A', 'C');
graph.addEdge('B', 'D');
graph.addEdge('C', 'E');
graph.addEdge('D', 'E');
graph.addEdge('D', 'F');
graph.addEdge('E', 'F');
console.log('BFS traversal starting from A:', graph.bfs('A'));
// Output: ['A', 'B', 'C', 'D', 'E', 'F']
console.log('Shortest path from A to F:', graph.bfsShortestPath('A', 'F'));
// Output: ['A', 'B', 'D', 'F']
// BFS for a tree/binary tree
function bfsTree(root) {
if (!root) return [];
const queue = [root];
const result = [];
while (queue.length) {
const node = queue.shift();
result.push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
return result;
}
// Example tree node structure
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
// Create a simple tree
const root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
console.log('BFS tree traversal:', bfsTree(root));
// Output: [1, 2, 3, 4, 5]