-
Notifications
You must be signed in to change notification settings - Fork 0
/
graphDFS.js
107 lines (87 loc) · 2.44 KB
/
graphDFS.js
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
// depthFirstSearch - this function should return an array of nodes visited using DFS.
// You can do this iteratively (using a stack) or recursively, but note the order of the results will be different. The test cases should accommodate this.
function Graph() {
this.adjacencyList = {};
}
Graph.prototype.numEdges = function() {
let total = 0;
Object.values(this.adjacencyList).forEach(list => {
total += list.length;
});
return total / 2;
};
Graph.prototype.addVertex = function(vertex) {
this.adjacencyList[vertex] = [];
};
Graph.prototype.addEdge = function(vertex1, vertex2) {
this.adjacencyList[vertex1].push(vertex2);
this.adjacencyList[vertex2].push(vertex1);
};
Graph.prototype.removeVertex = function(vertex) {
while (this.adjacencyList[vertex].length) {
const adjacentVertex = this.adjacencyList[vertex].pop();
this.removeEdge(adjacentVertex, vertex);
}
delete this.adjacencyList[vertex];
};
Graph.prototype.removeEdge = function(vertex1, vertex2) {
this.adjacencyList[vertex1] = this.adjacencyList[vertex1].filter(
v => v !== vertex2``
);
this.adjacencyList[vertex2] = this.adjacencyList[vertex2].filter(
v => v !== vertex1
);
};
// Iteratively
Graph.prototype.depthFirstSearch = function(start) {
let stack = [start];
let result = [];
let visited = new Set(stack);
while (stack.length) {
let vertex = stack.pop();
result.push(vertex);
let adjacencyList = this.adjacencyList[vertex];
for (let v of adjacencyList) {
if (!visited.has(v)) {
visited.add(v);
stack.push(v);
}
}
}
return result;
};
// Testing Setup
var graph = new Graph();
graph.addVertex("S");
graph.addVertex("P");
graph.addVertex("U");
graph.addVertex("X");
graph.addVertex("Q");
graph.addVertex("Y");
graph.addVertex("V");
graph.addVertex("R");
graph.addVertex("W");
graph.addVertex("T");
graph.addEdge("S", "P");
graph.addEdge("S", "U");
graph.addEdge("P", "X");
graph.addEdge("U", "X");
graph.addEdge("P", "Q");
graph.addEdge("U", "V");
graph.addEdge("X", "Q");
graph.addEdge("X", "Y");
graph.addEdge("X", "V");
graph.addEdge("Q", "R");
graph.addEdge("Y", "R");
graph.addEdge("Y", "W");
graph.addEdge("V", "W");
graph.addEdge("R", "T");
graph.addEdge("W", "T");
console.log(graph.depthFirstSearch("S"));
/**
* results:
*
* ["S", "P", "X", "U", "V", "W", "Y", "R", "Q", "T"] // recursive version
* ["S", "U", "V", "W", "T", "R", "Q", "Y", "X", "P"] // iterative (stack) version
*
**/