-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.js
More file actions
52 lines (46 loc) · 1.16 KB
/
graph.js
File metadata and controls
52 lines (46 loc) · 1.16 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
class Graph {
constructor() {
this.adjList = new Map();
}
addVertex(vertex) {
if (!this.adjList.has(vertex)) {
this.adjList.set(vertex, []);
}
}
addEdge(vertex1, vertex2) {
this.addVertex(vertex1);
this.addVertex(vertex2);
this.adjList.get(vertex1).push(vertex2);
this.adjList.get(vertex2).push(vertex1); // Remove this for a directed graph
}
printGraph() {
for (let [vertex, edges] of this.adjList.entries()) {
console.log(`${vertex} -> ${edges.join(", ")}`);
}
}
bfs(start) {
const visited = new Set();
const queue = [start];
while (queue.length) {
const vertex = queue.shift();
if (!visited.has(vertex)) {
console.log(vertex);
visited.add(vertex);
const neighbors = this.adjList.get(vertex);
for (let neighbor of neighbors) {
if (!visited.has(neighbor)) {
queue.push(neighbor);
}
}
}
}
}
dfs(start, visited = new Set()) {
if (visited.has(start)) return;
console.log(start);
visited.add(start);
for (let neighbor of this.adjList.get(start)) {
this.dfs(neighbor, visited);
}
}
}