-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.js
More file actions
102 lines (91 loc) · 2.28 KB
/
graph.js
File metadata and controls
102 lines (91 loc) · 2.28 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
class Graph {
constructor(){
this.adjacencyList = {};
}
addVertex(name){
this.adjacencyList[name] = [];
}
addEdge(vertex1, vertex2){
this.adjacencyList[vertex1].push(vertex2);
this.adjacencyList[vertex2].push(vertex1);
}
removeEdge(vertex1, vertex2){
this.adjacencyList[vertex1] = this.adjacencyList[vertex1].filter(value => value !== vertex2);
this.adjacencyList[vertex2] = this.adjacencyList[vertex2].filter(value => value !== vertex1 )
}
removeVertex(vertex){
while(this.adjacencyList[vertex].length > 0){
this.removeEdge(vertex, this.adjacencyList[vertex].pop());
}
delete this.adjacencyList[vertex];
}
DFSRecursive(start){
let result = [];
let visited = {};
let list = this.adjacencyList;
function DFSHelper(vertex){
if(!vertex) return;
visited[vertex] = true;
result.push(vertex);
for(let value of list[vertex]){
if(!visited[value]){
DFSHelper(value);
}
}
}
DFSHelper(start);
return result;
}
DFSIterative(start){
let result = [];
let visited = {};
let stack = [];
stack.push(start);
visited[start] = true;
while(stack.length){
console.log("here");
let currentVertex = stack.pop();
result.push(currentVertex);
for(let neighbor of this.adjacencyList[currentVertex]){
if(!visited[neighbor]){
visited[neighbor] = true;
stack.push(neighbor);
}
}
}
return result;
}
BFS(start){
let queue = [start];
let visited = {};
let result = [];
visited[start] = true;
while(queue.length){
let currentVertex = queue.shift();
result.push(currentVertex);
for(let neighbor of this.adjacencyList[currentVertex]){
if(!visited[neighbor]){
visited[neighbor] = true;
queue.push(neighbor);
}
}
}
return result;
}
}
const graph = new Graph();
graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("C");
graph.addVertex("D");
graph.addVertex("E");
graph.addVertex("F");
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(graph)
console.log(graph.BFS("A"));