The Top 10 Algorithms Every Programmer Should Know In Graph Data Structure!
Tags: algorithms, cpp, programming, beginners
Published: 2022-02-09 09:36:20

## Why to learn these graph algorithms?
        
Graph algorithms are a set of instructions that traverse (visits nodes of a) graph. Some algorithms are used to find a specific node or the path between two given nodes.

Graphs are very useful data structures which can be to model various problems. These algorithms have direct applications on Social Networking sites, State Machine modeling and many more. I have attached my source code for all the algorithms discussed below. You can use it for your referral. 


### 1. Breadth First Searching

**Breadth First Search** is a recursive algorithm for searching all the vertices of a graph or tree data structure.
Breadth-first search is a graph traversal algorithm that starts traversing the graph from the root node and explores all the neighboring nodes. Then, it selects the nearest node and explores all the unexplored nodes. While using BFS for traversal, any node in the graph can be considered as the root node.

**An simple algorithm to be remembered for BFS:**

1. Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a queue.

2. If no adjacent vertex is found, remove the first vertex from the queue.

3. Repeat Rule 1 and Rule 2 until the queue is empty.

**The Diagrammatic representation of BFS Traversal:**


![bfs.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1644347005226/ePwZ0LVJF.jpeg)

**Reference code :** [Breadth First Searching](https://github.com/RajKousik/GraphDataStructure/blob/main/BFSTraversal.cpp)



### 2. Depth First Searching

Depth first Search or Depth first traversal is a recursive algorithm for searching all the vertices of a graph or tree data structure. 
Depth First Search (DFS) algorithm traverses a graph in a depthward motion and uses a stack to remember to get the next vertex to start a search, when a dead end occurs in any iteration.

**An simple algorithm to be remembered for DFS:**

1. Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a stack.

2. If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up all the vertices from the stack, which do not have adjacent vertices.)

3. Repeat Rule 1 and Rule 2 until the stack is empty.

**The Diagrammatic representation of DFS Traversal:**


![dfs.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1644347262649/QRSUdEvSD.jpeg)

**Reference code :** [Depth First Searching](https://github.com/RajKousik/GraphDataStructure/blob/main/DFSTraversal.cpp)


### 3. Topological Sorting

Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge u v, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.
There can be more than one topological sorting for a graph.

**An simple algorithm to be remembered for Topological sort:**

   1. mark u as visited

   2. for all vertices v which is adjacent with u, do

   2.1 if v is not visited, then

   2.2 TopoSort(c, visited, stack)

   2.3 done

   3. push u into a stack


**The Diagrammatic representation of Topological sort**

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1644347962433/isQhR1CxR.png)

**One of the Topological sort for this graph is:**

5 -> 4 -> 2 -> 3 -> 1 -> 0

**Reference code :** [Topological Sorting](https://github.com/RajKousik/GraphDataStructure/blob/main/TopologicalSort.cpp)



### 4. Detecting a cycle using Kahn's Algorithm  

Kahn’s topological sort algorithm is cycle detection algorithm, which also provides an efficient way to print the topological order.
Kahn’s topological sort algorithm works by finding vertices with no incoming edges and removing all outgoing edges from these vertices.

**Reference code :** [Detecting a cycle using Kahn's Algorithm](https://github.com/RajKousik/GraphDataStructure/blob/main/CycleDetection.cpp)



### 5. Dijkstra's Algorithm

Dijkstra's algorithm allows us to find the shortest path between any two vertices of a graph.
It differs from the minimum spanning tree because the shortest distance between two vertices might not include all the vertices of the graph.

It is a single-source shortest path algorithm. Here, single-source means that only one source is given, and we have to find the shortest path from the source to all the nodes.


![dik1.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1644348986664/0G1xuDPrU.jpeg)

After applying Dijkstra's Algorithm:

![dik2.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1644348996710/6DA6Oq-El.jpeg)

**Reference code :** [Dijkstra's Algorithm](https://github.com/RajKousik/GraphDataStructure/blob/main/Dijkstra'sAlgorithm.cpp)



### 6. Bellman Ford's Algorithm

Bellman Ford algorithm helps us find the shortest path from a vertex to all other vertices of a weighted graph.
It is similar to Dijkstra's algorithm but it can detect graphs in which edges can have negative weight cycles.

Dijkstra's Algorithm (can't able to detect negative weight cycle) can give an incorrect result because they can go through a negative weight cycle and reduce the path length.

Dijkstra doesn’t work for Graphs with negative weights, Bellman-Ford works for such graphs. Bellman-Ford is also simpler than Dijkstra and suites well for distributed systems.



![bell1.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1644349191573/UC8Jutlwf.jpeg)

The Output Of Bellman Ford's Algorithm:

![bell2.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1644349208711/7sinOsJGt.jpeg)

**Reference code :** [Bellman Ford's Algorithm](https://github.com/RajKousik/GraphDataStructure/blob/main/BellmanFord.cpp)



### 7. Floyd-Warshall Algorithm

Floyd-Warshall Algorithm is an algorithm for finding the shortest path between all the pairs of vertices in a weighted graph. This algorithm works for both the directed and undirected weighted graphs. But, it does not work for the graphs with negative cycles (where the sum of the edges in a cycle is negative). Here, a dynamic programming concept will be used.

Algorithm Behind Floyd-Warshall Algorithm:

Dij(k) ← min ( Dij(k-1), Dik(k-1)+Dkj(k-1) )

**Reference code :** [Floyd-Warshall Algorithm](https://github.com/RajKousik/GraphDataStructure/blob/main/FLoydWarshall.cpp)



### 8. Prim's Algorithm

Prim's Algorithm is a greedy algorithm that is used to find the minimum spanning tree from a graph. Prim's algorithm finds the subset of edges that includes every vertex of the graph such that the sum of the weights of the edges can be minimized.

****An simple algorithm to be remembered for Prim's Algorithm:****

1. Initialize the minimum spanning tree with a vertex chosen at random.

2. Find all the edges that connect the tree to new vertices, find the minimum and add it to the tree.

3. Keep repeating step 2 until we get a minimum spanning tree




![prim1.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1644383396035/DVZKgQTNq.jpeg)

**Output:**

![prim2.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1644383428636/BP41C4Ke7.jpeg)

**Reference code :** [Prim's Algorithm](https://github.com/RajKousik/GraphDataStructure/blob/main/PrimsAlgo.cpp)



### 9. Kruskal's Algorithm


Kruskal's Algorithm is used to find the minimum spanning tree for a connected weighted graph. The main target of the algorithm is to find the subset of edges by using which we can traverse every vertex of the graph. It follows the greedy approach that finds an optimum solution at every stage instead of focusing on a global optimum.

**An simple algorithm to be remembered for Prim's Algorithm:**

1. First, sort all the edges from low weight to high.

2. Now, take the edge with the lowest weight and add it to the spanning tree. If the edge to be added creates a cycle, then reject the edge.

3. Continue to add the edges until we reach all vertices, and a minimum spanning tree is created.

**Reference code :** [Kruskal's Algorithm](https://github.com/RajKousik/GraphDataStructure/blob/main/KruskalsAlgo.cpp)



### 10. Kosaraju's Algorithm


If we can reach every vertex of a component from every other vertex in that component then it is called a Strongly Connected Component (SCC). Single node is always a SCC. The Brute force method will be Floyd Warshall Algorithm. But for better time complexity, we can use Kosaraju's Algorithm.

**An simple algorithm to be remembered for Prim's Algorithm:**

1. Perform DFS traversal of the graph. Push node to stack before returning.

2. Find the transpose graph by reversing the edges.

3. Pop nodes one by one from the stack and again to DFS on the modified graph.



![kosa1.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1644384005676/QvPPRY0ii.jpeg)

**Output:**

![kosa2.jpg](https://cdn.hashnode.com/res/hashnode/image/upload/v1644384013067/PuN--mHzO.jpeg)

**Reference code :** [Kosaraju's Algorithm](https://github.com/RajKousik/GraphDataStructure/blob/main/Kosaraju'sAlgo.cpp)



These are the most important algorithms one should know as a programmer in graph data structure.
I will be uploading detailed explanation of each algorithm in upcoming posts. Stay Tuned!


Did you find the Algorithms listed in this article helpful?
If you enjoyed this article, share it with your friends and colleagues! 
Leave your comments below!

Here's my another article: [Learn Data Structures and Algorithms](https://kousikraj.hashnode.dev/learn-data-structures-and-algorithms)