Given a Weighted Directed Acyclic Graph and a source vertex in the graph, find the shortest paths from given source to all other vertices.
For a general weighted graph, we can calculate single source shortest distances in O(VE) time using Bellman–Ford Algorithm. For a graph with no negative weights, we can do better and calculate single source shortest distances in O(E + VLogV) time using Dijkstra’s algorithm. Can we do even better for Directed Acyclic Graph (DAG)? We can calculate single source shortest distances in O(V+E) time for DAGs. The idea is to use Topological Sorting.

We initialize distances to all vertices as infinite and distance to source as 0, then we find a topological sorting of the graph. Topological Sorting of a graph represents a linear ordering of the graph (See below, figure (b) is a linear representation of figure (a) ). Once we have topological order (or linear representation), we one by one process all vertices in topological order. For every vertex being processed, we update distances of its adjacent using distance of current vertex.

Following figure is taken from this source. It shows step by step process of finding shortest paths.

Following is complete algorithm for finding shortest distances.
1) Initialize dist[] = {INF, INF, ….} and dist[s] = 0 where s is the source vertex.
2) Create a toplogical order of all vertices.
3) Do following for every vertex u in topological order.
………..Do following for every adjacent vertex v of u
………………if (dist[v] > dist[u] + weight(u, v))
………………………dist[v] = dist[u] + weight(u, v)

// Java program to find single source shortest paths in Directed Acyclic Graphs
import java.io.*;
import java.util.*; class ShortestPath
{
static final int INF=Integer.MAX_VALUE;
class AdjListNode
{
private int v;
private int weight;
AdjListNode(int _v, int _w) { v = _v; weight = _w; }
int getV() { return v; }
int getWeight() { return weight; }
} // Class to represent graph as an adjcency list of
// nodes of type AdjListNode
class Graph
{
private int V;
private LinkedList<AdjListNode>adj[];
Graph(int v)
{
V=v;
adj = new LinkedList[V];
for (int i=0; i<v; ++i)
adj[i] = new LinkedList<AdjListNode>();
}
void addEdge(int u, int v, int weight)
{
AdjListNode node = new AdjListNode(v,weight);
adj[u].add(node);// Add v to u's list
} // A recursive function used by shortestPath.
// See below link for details
void topologicalSortUtil(int v, Boolean visited[], Stack stack)
{
// Mark the current node as visited.
visited[v] = true;
Integer i; // Recur for all the vertices adjacent to this vertex
Iterator<AdjListNode> it = adj[v].iterator();
while (it.hasNext())
{
AdjListNode node =it.next();
if (!visited[node.getV()])
topologicalSortUtil(node.getV(), visited, stack);
}
// Push current vertex to stack which stores result
stack.push(new Integer(v));
} // The function to find shortest paths from given vertex. It
// uses recursive topologicalSortUtil() to get topological
// sorting of given graph.
void shortestPath(int s)
{
Stack stack = new Stack();
int dist[] = new int[V]; // Mark all the vertices as not visited
Boolean visited[] = new Boolean[V];
for (int i = 0; i < V; i++)
visited[i] = false; // Call the recursive helper function to store Topological
// Sort starting from all vertices one by one
for (int i = 0; i < V; i++)
if (visited[i] == false)
topologicalSortUtil(i, visited, stack); // Initialize distances to all vertices as infinite and
// distance to source as 0
for (int i = 0; i < V; i++)
dist[i] = INF;
dist[s] = 0; // Process vertices in topological order
while (stack.empty() == false)
{
// Get the next vertex from topological order
int u = (int)stack.pop(); // Update distances of all adjacent vertices
Iterator<AdjListNode> it;
if (dist[u] != INF)
{
it = adj[u].iterator();
while (it.hasNext())
{
AdjListNode i= it.next();
if (dist[i.getV()] > dist[u] + i.getWeight())
dist[i.getV()] = dist[u] + i.getWeight();
}
}
} // Print the calculated shortest distances
for (int i = 0; i < V; i++)
{
if (dist[i] == INF)
System.out.print( "INF ");
else
System.out.print( dist[i] + " ");
}
}
} // Method to create a new graph instance through an object
// of ShortestPath class.
Graph newGraph(int number)
{
return new Graph(number);
} public static void main(String args[])
{
// Create a graph given in the above diagram. Here vertex
// numbers are 0, 1, 2, 3, 4, 5 with following mappings:
// 0=r, 1=s, 2=t, 3=x, 4=y, 5=z
ShortestPath t = new ShortestPath();
Graph g = t.newGraph(6);
g.addEdge(0, 1, 5);
g.addEdge(0, 2, 3);
g.addEdge(1, 3, 6);
g.addEdge(1, 2, 2);
g.addEdge(2, 4, 4);
g.addEdge(2, 5, 2);
g.addEdge(2, 3, 7);
g.addEdge(3, 4, -1);
g.addEdge(4, 5, -2); int s = 1;
System.out.println("Following are shortest distances "+
"from source " + s );
g.shortestPath(s);
}
}

Output:

Following are shortest distances from source 1
INF 0 2 6 5 3

Time Complexity: Time complexity of topological sorting is O(V+E). After finding topological order, the algorithm process all vertices and for every vertex, it runs a loop for all adjacent vertices. Total adjacent vertices in a graph is O(E). So the inner loop runs O(V+E) times. Therefore, overall time complexity of this algorithm is O(V+E).

algorithm@ Shortest Path in Directed Acyclic Graph (O(|V|+|E|) time)的更多相关文章

  1. 拓扑排序-有向无环图(DAG, Directed Acyclic Graph)

    条件: 1.每个顶点出现且只出现一次. 2.若存在一条从顶点 A 到顶点 B 的路径,那么在序列中顶点 A 出现在顶点 B 的前面. 有向无环图(DAG)才有拓扑排序,非DAG图没有拓扑排序一说. 一 ...

  2. AOJ GRL_1_C: All Pairs Shortest Path (Floyd-Warshall算法求任意两点间的最短路径)(Bellman-Ford算法判断负圈)

    题目链接:http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_1_C All Pairs Shortest Path Input ...

  3. AOJ GRL_1_A: Single Source Shortest Path (Dijktra算法求单源最短路径,邻接表)

    题目链接:http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_1_A Single Source Shortest Path In ...

  4. The Shortest Path in Nya Graph

    Problem Description This is a very easy problem, your task is just calculate el camino mas corto en ...

  5. (中等) HDU 4725 The Shortest Path in Nya Graph,Dijkstra+加点。

    Description This is a very easy problem, your task is just calculate el camino mas corto en un grafi ...

  6. HDU 4725 The Shortest Path in Nya Graph (最短路)

    The Shortest Path in Nya Graph Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K ...

  7. Proof for Floyd-Warshall's Shortest Path Derivation Algorithm Also Demonstrates the Hierarchical Path Construction Process

    (THIS BLOG WAS ORIGINALLY WRTITTEN IN CHINESE WITH LINK: http://www.cnblogs.com/waytofall/p/3732920. ...

  8. The Shortest Path in Nya Graph HDU - 4725

    Problem Description This is a very easy problem, your task is just calculate el camino mas corto en ...

  9. HDU 4725 The Shortest Path in Nya Graph(最短路径)(2013 ACM/ICPC Asia Regional Online ―― Warmup2)

    Description This is a very easy problem, your task is just calculate el camino mas corto en un grafi ...

随机推荐

  1. 使用 Async 和 Await 的异步编程

    来自:http://msdn.microsoft.com/library/vstudio/hh191443   异步对可能起阻止作用的活动(例如,应用程序访问 Web 时)至关重要. 对 Web 资源 ...

  2. JS代码片段:一个日期离现在多久了

    var dateDiff = function(hisTime,nowTime){ if(!arguments.length) return ''; var arg = arguments, now ...

  3. UVa 11524 - InCircle

    推公式 #include <cstdio> #include <cmath> double Cal( double a, double b, double c ) { retu ...

  4. MyEclipse开发WebService教程

    . 创建一个 webService 工程. 2. 创建一个普通 Java 类   3. 创建 webService 服务端 HelloJaxwsDelegate.java 的源代码如下:   4. 导 ...

  5. 自定义sublime代码片段

    sublime text 已经有一些他们内置的一些代码片段,但是有时候,这些并不能满足我们,这就需要我们自定义一些代码片段. 步骤如下: 1.打开sublime text 2.选择 tools -&g ...

  6. POJ 1753 Flip Game (高斯消元 枚举自由变元求最小步数)

    题目链接 题意:4*4的黑白棋,求把棋全变白或者全变黑的最小步数. 分析:以前用状态压缩做过. 和上题差不多,唯一的不同是这个终态是黑棋或者白棋, 但是只需要把给的初态做不同的两次处理就行了. 感觉现 ...

  7. Ural1076(km算法)

    题目大意 给出n*n表格,第a[i,j]表示i到j的权值,现在我们要将每个a[i,j]=sum[j]-a[i,j], 求出当前二分图a[][]最小匹配 最小匹配只需将权值取负后,求二分图最大匹配,使用 ...

  8. springMVC传对象参数、返回JSON格式数据

    假如请求路径:http://localhost/test/test.do?user.id=1 后台接收参数的方法如下: @RequestMapping("/test") publi ...

  9. Jqgrid入门-结合Struts2+json实现数据展示(五)

    DEMO用的是ssh框架实现的,具体怎么搭建的就不多做说明了.分页表格的数据操作难点就是数据展现.至于增删改直接用hibernate原生的方法实现即可.         初步分析:表格要实现分页,那么 ...

  10. I.MX6 Ethernet UI patch failed

    /*********************************************************************** * I.MX6 Ethernet UI patch f ...