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

Class Graph

Data-Structures/Graph/Graph2.js:2–60  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1// create a graph class
2class Graph {
3 // defining vertex array and
4 // adjacent list
5 constructor(noOfVertices) {
6 this.noOfVertices = noOfVertices
7 this.AdjList = new Map()
8 }
9
10 // functions to be implemented
11
12 // addVertex(v)
13 // addEdge(v, w)
14 // printGraph()
15
16 // bfs(v)
17 // dfs(v)
18
19 // add vertex to the graph
20 addVertex(v) {
21 // initialize the adjacent list with a
22 // null array
23
24 this.AdjList.set(v, [])
25 }
26
27 // add edge to the graph
28 addEdge(v, w) {
29 // get the list for vertex v and put the
30 // vertex w denoting edge between v and w
31 this.AdjList.get(v).push(w)
32
33 // Since graph is undirected,
34 // add an edge from w to v also
35 this.AdjList.get(w).push(v)
36 }
37
38 // Prints the vertex and adjacency list
39 printGraph(output = (value) => console.log(value)) {
40 // get all the vertices
41 const getKeys = this.AdjList.keys()
42
43 // iterate over the vertices
44 for (const i of getKeys) {
45 // get the corresponding adjacency list
46 // for the vertex
47 const getValues = this.AdjList.get(i)
48 let conc = ''
49
50 // iterate over the adjacency list
51 // concatenate the values into a string
52 for (const j of getValues) {
53 conc += j + ' '
54 }
55
56 // print the vertex and its adjacency list
57 output(i + ' -> ' + conc)
58 }
59 }
60}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected