# Implementation of Graph in JavaScript

In this article we would be implementing the Graph data structure in JavaScript. Graph is a non-linear data structure. A graph** G **contains a set of vertices** V **and set of Edges** E**. Graph has lots of application in computer science.

**Graph is basically divided into two broad categories :**

**Directed Graph (Di- graph)**– Where edges have direction.**Undirected Graph**– Where edges do not represent any directed

There are various ways to represent a Graph :-

**Adjacency Matrix****Adjacency List**

There are several other ways like incidence matrix, etc. but these two are most commonly used. Refer to Graph and its representations for the explaination of Adjacency matrix and list.

In this article, we would be using **Adjacency List** to represent a graph because in most cases it has a certain advantage over the other representation.

Now Lets see an example of Graph class-

`// create a graph class ` `class` `Graph { ` ` ` `// defining vertex array and ` ` ` `// adjacent list ` ` ` `constructor(noOfVertices) ` ` ` `{ ` ` ` `this` `.noOfVertices = noOfVertices; ` ` ` `this` `.AdjList = ` `new` `Map(); ` ` ` `} ` ` ` ` ` `// functions to be implemented ` ` ` ` ` `// addVertex(v) ` ` ` `// addEdge(v, w) ` ` ` `// printGraph() ` ` ` ` ` `// bfs(v) ` ` ` `// dfs(v) ` `} ` |

*chevron_right*

*filter_none*

The above example shows a framework of *Graph* class. We define two private variable i.e *noOfVertices* to store the number of vertices in the graph and *AdjList*, which stores a adjacency list of a particular vertex. We used a **Map** Object provided by ES6 in order to implement Adjacency list. Where key of a map holds a vertex and values holds an array of an adjacent node.

Now let’s implement functions to perform basic operations on the graph:

**addVertex(v)**– It adds the vertex*v*as key to*adjList*and initialize its values with an array.`// add vertex to the graph`

`addVertex(v)`

`{`

`// initialize the adjacent list with a`

`// null array`

`this`

`.AdjList.set(v, []);`

`}`

*chevron_right**filter_none***addEdge(src, dest)**– It adds an edge between the*src*and*dest*.`// add edge to the graph`

`addEdge(v, w)`

`{`

`// get the list for vertex v and put the`

`// vertex w denoting edge between v and w`

`this`

`.AdjList.get(v).push(w);`

`// Since graph is undirected,`

`// add an edge from w to v also`

`this`

`.AdjList.get(w).push(v);`

`}`

*chevron_right**filter_none*In order to add edge we get the adjacency list of the corresponding

*src*vertex and add the*dest*to the adjacency list.**printGraph()**– It prints vertices and its adjacency list.`// Prints the vertex and adjacency list`

`printGraph()`

`{`

`// get all the vertices`

`var get_keys =`

`this`

`.AdjList.keys();`

`// iterate over the vertices`

`for`

`(var i of get_keys)`

`{`

`// great the corresponding adjacency list`

`// for the vertex`

`var get_values =`

`this`

`.AdjList.get(i);`

`var conc =`

`""`

`;`

`// iterate over the adjacency list`

`// concatenate the values into a string`

`for`

`(var j of get_values)`

`conc += j +`

`" "`

`;`

`// print the vertex and its adjacency list`

`console.log(i +`

`" -> "`

`+ conc);`

`}`

`}`

*chevron_right**filter_none*

Lets see an example of a graph

Now we will use the graph class to implement the graph shown above:

`// Using the above implemented graph class ` `var g = ` `new` `Graph(` `6` `); ` `var vertices = [ ` `'A'` `, ` `'B'` `, ` `'C'` `, ` `'D'` `, ` `'E'` `, ` `'F'` `]; ` ` ` `// adding vertices ` `for` `(var i = ` `0` `; i < vertices.length; i++) { ` ` ` `g.addVertex(vertices[i]); ` `} ` ` ` `// adding edges ` `g.addEdge(` `'A'` `, ` `'B'` `); ` `g.addEdge(` `'A'` `, ` `'D'` `); ` `g.addEdge(` `'A'` `, ` `'E'` `); ` `g.addEdge(` `'B'` `, ` `'C'` `); ` `g.addEdge(` `'D'` `, ` `'E'` `); ` `g.addEdge(` `'E'` `, ` `'F'` `); ` `g.addEdge(` `'E'` `, ` `'C'` `); ` `g.addEdge(` `'C'` `, ` `'F'` `); ` ` ` `// prints all vertex and ` `// its adjacency list ` `// A -> B D E ` `// B -> A C ` `// C -> B E F ` `// D -> A E ` `// E -> A D F C ` `// F -> E C ` `g.printGraph(); ` |

*chevron_right*

*filter_none*

**Graph Traversal**

We will implement the most common graph traversal algorithm:

Implementation of BFS and DFS:

**bfs(startingNode)**– It performs Breadth First Search from the given*startingNode*`// function to performs BFS`

`bfs(startingNode)`

`{`

`// create a visited array`

`var visited = [];`

`for`

`(var i =`

`0`

`; i <`

`this`

`.noOfVertices; i++)`

`visited[i] =`

`false`

`;`

`// Create an object for queue`

`var q =`

`new`

`Queue();`

`// add the starting node to the queue`

`visited[startingNode] =`

`true`

`;`

`q.enqueue(startingNode);`

`// loop until queue is element`

`while`

`(!q.isEmpty()) {`

`// get the element from the queue`

`var getQueueElement = q.dequeue();`

`// passing the current vertex to callback funtion`

`console.log(getQueueElement);`

`// get the adjacent list for current vertex`

`var get_List =`

`this`

`.AdjList.get(getQueueElement);`

`// loop through the list and add the element to the`

`// queue if it is not processed yet`

`for`

`(var i in get_List) {`

`var neigh = get_List[i];`

`if`

`(!visited[neigh]) {`

`visited[neigh] =`

`true`

`;`

`q.enqueue(neigh);`

`}`

`}`

`}`

`}`

*chevron_right**filter_none*In the above method we have implemented the BFS algorithm. A Queue is used to keep the unvisited nodes

Lets use the above method and traverse along the graph

`// prints`

`// BFS`

`// A B D E C F`

`console.log(`

`"BFS"`

`);`

`g.bfs(`

`'A'`

`);`

*chevron_right**filter_none*The Diagram below shows the BFS on the example graph:

**dfs(startingNode)**– It performs the Depth first traversal on a graph`// Main DFS method`

`dfs(startingNode)`

`{`

`var visited = [];`

`for`

`(var i =`

`0`

`; i <`

`this`

`.noOfVertices; i++)`

`visited[i] =`

`false`

`;`

`this`

`.DFSUtil(startingNode, visited);`

`}`

`// Recursive function which process and explore`

`// all the adjacent vertex of the vertex with which it is called`

`DFSUtil(vert, visited)`

`{`

`visited[vert] =`

`true`

`;`

`console.log(vert);`

`var get_neighbours =`

`this`

`.AdjList.get(vert);`

`for`

`(var i in get_neighbours) {`

`var get_elem = get_neighbours[i];`

`if`

`(!visited[get_elem])`

`this`

`.DFSUtil(get_elem, visited);`

`}`

`}`

*chevron_right**filter_none*In the above example

*dfs(startingNode)*is used to initialize a visited array and*DFSutil(vert, visited)*

contains the implementation of DFS algorithm

Lets use the above method to traverse along the graph`// prints`

`// DFS`

`// A B C E D F`

`console.log(`

`"DFS"`

`);`

`g.dfs(`

`'A'`

`);`

*chevron_right**filter_none*The Diagram below shows the DFS on the example graph

This article is contributed by **Sumit Ghosh**. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

## Recommended Posts:

- Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
- Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
- Implementation of Stack in JavaScript
- Implementation of Queue in Javascript
- Implementation of LinkedList in Javascript
- Implementation of Priority Queue in Javascript
- Implementation of Array class in JavaScript
- Implementation of Binary Search Tree in Javascript
- Convert the undirected graph into directed graph such that there is no path of length greater than 1
- Maximum number of edges that N-vertex graph can have such that graph is Triangle free | Mantel's Theorem
- Detect cycle in the graph using degrees of nodes of graph
- Convert undirected connected graph to strongly connected directed graph
- Implementation of BFS using adjacency matrix
- Traveling Salesman Problem (TSP) Implementation
- Push Relabel Algorithm | Set 2 (Implementation)