Floyd algorithm

Algorithm

The Floyed algorithm is an algorithm for efficiently and simultaneously finding the shortest paths betweeen every pair of vertices in a weighted and potentially directed graph.

Consider a graph G with vertices V,each numbered 1 through N. Further consider a function shortestPath(i,j,k) that return the shortest possible path from i to j using vertices only from the set {1,2,....k}  as intermediate point along the way. Now ,given this function ,our goal is to find the  shorttest  path from each i to each j using only vertices 1 to k+1.And the fuction what we want is called Floyed algorithm.

For each of these pairs of  vertices,the true shortest path could be either (1) a path that only uses vertices in the set {1,....,k} or (2) a path that goes from i to k+1 and then from k+1 to j.We know that the best path from i to j that uses vertices 1 through k is defined by shortestPath(i,j,k),and it is clear that if there were a better path from i to k+1 to j,then the length of this path would be  the concatenation of the shortest path from i to k+1(uing vertices in {1,....,k} and shortest path from k+1 to  j (also using vertices in {1,...,k}).

If w(i,j) is the weight of the edge between vertices i and j,we can define shortestPath(i,j,k) in terms of the following recursive  formula :the base case is

shortestPath(i,j,0)=w(i,j)

and the recursive case is

shortestPath(i,j,k)=min(shortestPath(i,j,k-1),shortestPath(i,k,k-1)+shortestPath(k,j,k-1)):

This formula is the heart of the Floyed algorithm. The algorithm works by first computer shortestPath(i,j,k) for all (i,j) pairs for k=1,then k=2,etc.This process continue until k=n,and we have found the shortest path for all (i,j) pairs using any intermediate vertices.

code :

 1 procedure FloydWarshallWithPathReconstruction ()
 2    for k := 1 to n
 3       for i := 1 to n
 4          for j := 1 to n
 5             if path[i][k] + path[k][j] < path[i][j] then {
 6                path[i][j] := path[i][k]+path[k][j];
 7                next[i][j] := k; }
 8
 9 function Path (i,j)
10    if path[i][j] equals infinity then
11      return "no path";
12    int intermediate := next[i][j];
13    if intermediate equals 'null' then
14      return " ";   /* there is an edge from i to j, with no vertices between */
15    else
16      return Path(i,intermediate) + intermediate + Path(intermediate,j);

Applications and generalizations

The Floyd–Warshall algorithm can be used to solve the following problems, among others:

Case problem:

Now ,give you a problem and use the Floyd algorithm to slove it.Maybe it's helpful for you further understanding the algorithm!

http://www.cnblogs.com/heat-man/articles/2743401.html

Refefience:

http://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm

 

转载于:https://www.cnblogs.com/heat-man/articles/2743094.html

完成以下代码:""" File: fromexample.py Project 12.9 Defines and tests the all pairs shortest paths algorithm of Floyd. Uses the graph from Figure 12.19 of the text, as represented in the file example.txt. """ from graph import LinkedDirectedGraph import random from arrays import Array # Functions for working with infinity def isLessWithInfinity(a, b): """Returns False if a == b or a == INFINITY and b != INFINITY. Otherwise, returns True if b == INFINITY or returns a < b.""" if a == LinkedDirectedGraph.INFINITY and b == LinkedDirectedGraph.INFINITY: return False elif b == LinkedDirectedGraph.INFINITY: return True elif a == LinkedDirectedGraph.INFINITY: return False else: return a < b def addWithInfinity(a, b): """If a == INFINITY or b == INFINITY, returns INFINITY. Otherwise, returns a + b.""" if a == LinkedDirectedGraph.INFINITY or b == LinkedDirectedGraph.INFINITY: return LinkedDirectedGraph.INFINITY else: return a + b def minDistance(a, b): if isLessWithInfinity(a, b): return a else: return b # Define a function that uses Floyd's algorithm def allPairsShortestPaths(matrix): """ please complete the Floyd algorithm here """ pass # Define a function to print a labeled distance matrix def printDistanceMatrix(matrix, table): """Prints the distance matrix with rows and columns labels with the index positions and vertex labels.""" labels = Array(len(table)) index = 0 labelWidth = 0 indexWidth = 0 for label in table: labels[table[label]] = label labelWidth = max(labelWidth, len(str(label))) indexWidth = max(indexWidth, len(str(index))) index += 1 weightWidth = 0 for row in range(matrix.getHeight()): for column in range(matrix.getWidth()): weightWidth = max(weightWidth, len(str(matrix[row][column]))) weightWidth = max(weightWidth, labelWidth, indexWidth) topRowLeftMargin
04-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值