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

Class Graph

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

Source from the content-addressed store, hash-verified

1class Graph {
2 constructor() {
3 this.adjacencyObject = {}
4 }
5
6 addVertex(vertex) {
7 if (!this.adjacencyObject[vertex]) this.adjacencyObject[vertex] = []
8 }
9
10 addEdge(vertex1, vertex2) {
11 this.adjacencyObject[vertex1].push(vertex2)
12 this.adjacencyObject[vertex2].push(vertex1)
13 }
14
15 removeEdge(vertex1, vertex2) {
16 this.adjacencyObject[vertex1] = this.adjacencyObject[vertex1].filter(
17 (v) => v !== vertex2
18 )
19 this.adjacencyObject[vertex2] = this.adjacencyObject[vertex2].filter(
20 (v) => v !== vertex1
21 )
22 }
23
24 removeVertex(vertex) {
25 while (this.adjacencyObject[vertex].length) {
26 const adjacentVertex = this.adjacencyObject[vertex].pop()
27 this.removeEdge(vertex, adjacentVertex)
28 }
29 }
30
31 /**
32 * Return DFS (Depth First Search) List Using Recursive Method
33 */
34 DFS(start) {
35 if (!start) return null
36
37 const result = []
38 const visited = {}
39 const adjacencyObject = this.adjacencyObject
40
41 function dfs(vertex) {
42 if (!vertex) return null
43 visited[vertex] = true
44 result.push(vertex)
45 adjacencyObject[vertex].forEach((neighbor) => {
46 if (!visited[neighbor]) {
47 dfs(neighbor)
48 }
49 })
50 }
51
52 dfs(start)
53 return result
54 }
55
56 /**
57 * Return DFS(Depth First Search) List Using Iteration
58 */
59 DFSIterative(start) {
60 if (!start) return null

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected