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 explanation 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-
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.
- addEdge(src, dest) – It adds an edge between the src and dest.
- 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.
- Lets see an example of a graph
Now we will use the graph class to implement the graph shown above:
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
- 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
- The Diagram below shows the BFS on the example graph:
- dfs(startingNode) – It performs the Depth first traversal on a graph
- 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
- 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 write.geeksforgeeks.org or mail your article to firstname.lastname@example.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.