-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.js
More file actions
61 lines (50 loc) · 1.25 KB
/
DFS.js
File metadata and controls
61 lines (50 loc) · 1.25 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
// Depth-First Search
// DFS is a traversal algorithm that explores as far as possible
// along each branch before backtracking. It is often used to
// search for a path from a starting node to a goal node
// in a graph or tree.
class Graph {
constructor() {
this.nodes = [];
this.adjacencyList = [];
}
addNode(node) {
this.nodes.push(node);
this.adjacencyList[node] = [];
}
addEdge(node1, node2) {
this.adjacencyList[node1].push(node2);
this.adjacencyList[node2].push(node1);
}
dfs(start) {
const visited = {};
const result = [];
const adjacencyList = this.adjacencyList;
(function dfsVisit(vertex) {
if (!vertex) return null;
visited[vertex] = true;
result.push(vertex);
adjacencyList.forEach((neighbor) => {
if (!visited[neighbor]) {
return dfsVisit(neighbor);
}
});
})(start);
return result;
}
}
const graph = new Graph();
graph.addNode("A");
graph.addNode("B");
graph.addNode("C");
graph.addNode("D");
graph.addNode("E");
graph.addNode("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.dfs("A"));