Skip to content

Commit c98361b

Browse files
authored
Graph
1 parent 0713ebf commit c98361b

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed

maths/graph.js

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
// create a graph class
2+
class Graph {
3+
// defining vertex array and
4+
// adjacent list
5+
constructor(noOfVertices)
6+
{
7+
this.noOfVertices = noOfVertices;
8+
this.AdjList = new Map();
9+
}
10+
11+
// functions to be implemented
12+
13+
// addVertex(v)
14+
// addEdge(v, w)
15+
// printGraph()
16+
17+
// bfs(v)
18+
// dfs(v)
19+
}
20+
21+
// add vertex to the graph
22+
addVertex(v)
23+
{
24+
// initialize the adjacent list with a
25+
// null array
26+
this.AdjList.set(v, []);
27+
}
28+
29+
// add edge to the graph
30+
addEdge(v, w)
31+
{
32+
// get the list for vertex v and put the
33+
// vertex w denoting edge between v and w
34+
this.AdjList.get(v).push(w);
35+
36+
// Since graph is undirected,
37+
// add an edge from w to v also
38+
this.AdjList.get(w).push(v);
39+
}
40+
41+
42+
// Prints the vertex and adjacency list
43+
printGraph()
44+
{
45+
// get all the vertices
46+
var get_keys = this.AdjList.keys();
47+
48+
// iterate over the vertices
49+
for (var i of get_keys)
50+
{
51+
// great the corresponding adjacency list
52+
// for the vertex
53+
var get_values = this.AdjList.get(i);
54+
var conc = "";
55+
56+
// iterate over the adjacency list
57+
// concatenate the values into a string
58+
for (var j of get_values)
59+
conc += j + " ";
60+
61+
// print the vertex and its adjacency list
62+
console.log(i + " -> " + conc);
63+
}
64+
}
65+
66+
67+
// Example
68+
var graph = new Graph(6);
69+
var vertices = [ 'A', 'B', 'C', 'D', 'E', 'F' ];
70+
71+
// adding vertices
72+
for (var i = 0; i < vertices.length; i++) {
73+
g.addVertex(vertices[i]);
74+
}
75+
76+
// adding edges
77+
g.addEdge('A', 'B');
78+
g.addEdge('A', 'D');
79+
g.addEdge('A', 'E');
80+
g.addEdge('B', 'C');
81+
g.addEdge('D', 'E');
82+
g.addEdge('E', 'F');
83+
g.addEdge('E', 'C');
84+
g.addEdge('C', 'F');
85+
86+
// prints all vertex and
87+
// its adjacency list
88+
// A -> B D E
89+
// B -> A C
90+
// C -> B E F
91+
// D -> A E
92+
// E -> A D F C
93+
// F -> E C
94+
g.printGraph();

0 commit comments

Comments
 (0)