Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Longest Path in a Directed Acyclic Graph
One weighted directed acyclic graph is given. Another source vertex is also provided. Now we have to find the longest distance from the starting node to all other vertices, in the graph.


We need to sort the nodes in topological sorting technique, and the result after the topological sort is stored into a stack. After that repeatedly popped from the stack and try to find the longest distance for each vertex.
Input and Output
Input: The cost matrix of the graph. 0 5 3 -∞ -∞ -∞ -∞ 0 2 6 -∞ -∞ -∞ -∞ 0 7 4 2 -∞ -∞ -∞ 0 -1 1 -∞ -∞ -∞ -∞ 0 -2 -∞ -∞ -∞ -∞ -∞ 0 Output: Longest Distance from Source Vertex 1 Infinity 0 2 9 8 10
Algorithm
topoSort(u, visited, stack)
Input: starting node u, the visited list to keep track, the stack.
Output − Sort the nodes in a topological way.
Begin mark u as visited for all vertex v, which is connected with u, do if v is not visited, then topoSort(v, visited, stack) done push u into the stack End
longestPath(start)
Input − The starting node.
Output − List of longest distance of all vertices from the starting node.
Begin initially make all nodes as unvisited for each node i, in the graph, do if i is not visited, then topoSort(i, visited, stack) done make distance of all vertices as - ∞ dist[start] := 0 while stack is not empty, do pop stack item and take into nextVert if dist[nextVert] ≠ - ∞, then for each vertices v, which is adjacent with nextVert, do if cost[nextVert, v] ≠ - ∞, then if dist[v]Example
#include#include #define NODE 6 #define INF -9999 using namespace std; int cost[NODE][NODE] = { {0, 5, 3, INF, INF, INF}, {INF, 0, 2, 6, INF, INF}, {INF, INF, 0, 7, 4, 2}, {INF, INF, INF, 0, -1, 1}, {INF, INF, INF, INF, 0, -2}, {INF, INF, INF, INF, INF, 0} }; void topoSort(int u, bool visited[], stack &stk) { visited[u] = true; //set as the node v is visited for(int v = 0; v stk; int dist[NODE]; bool vis[NODE]; for(int i = 0; i Output
Longest Distance From Source Vertex 1 Infinity 0 2 9 8 10
Advertisements
