MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / Graph

Class Graph

Data-Structures/Graph/Graph.js:1–72  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class Graph {
2 constructor() {
3 this.adjacencyMap = {}
4 }
5
6 addVertex(vertex) {
7 this.adjacencyMap[vertex] = []
8 }
9
10 containsVertex(vertex) {
11 return typeof this.adjacencyMap[vertex] !== 'undefined'
12 }
13
14 addEdge(vertex1, vertex2) {
15 if (this.containsVertex(vertex1) && this.containsVertex(vertex2)) {
16 this.adjacencyMap[vertex1].push(vertex2)
17 this.adjacencyMap[vertex2].push(vertex1)
18 }
19 }
20
21 printGraph(output = (value) => console.log(value)) {
22 const keys = Object.keys(this.adjacencyMap)
23 for (const i of keys) {
24 const values = this.adjacencyMap[i]
25 let vertex = ''
26 for (const j of values) {
27 vertex += j + ' '
28 }
29 output(i + ' -> ' + vertex)
30 }
31 }
32
33 /**
34 * Prints the Breadth first traversal of the graph from source.
35 * @param {number} source The source vertex to start BFS.
36 */
37 bfs(source, output = (value) => console.log(value)) {
38 const queue = [[source, 0]] // level of source is 0
39 const visited = new Set()
40
41 while (queue.length) {
42 const [node, level] = queue.shift() // remove the front of the queue
43 if (visited.has(node)) {
44 // visited
45 continue
46 }
47
48 visited.add(node)
49 output(`Visited node ${node} at level ${level}.`)
50 for (const next of this.adjacencyMap[node]) {
51 queue.push([next, level + 1]) // level 1 more than current
52 }
53 }
54 }
55
56 /**
57 * Prints the Depth first traversal of the graph from source.
58 * @param {number} source The source vertex to start DFS.
59 */
60 dfs(source, visited = new Set(), output = (value) => console.log(value)) {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected