Floyd-Warshall 全源最短路径算法

时间:2023-03-08 19:00:35

Floyd-Warshall 算法采用动态规划方案来解决在一个有向图 G = (V, E) 上每对顶点间的最短路径问题,即全源最短路径问题(All-Pairs Shortest Paths Problem),其中图 G 允许存在权值为负的边,但不存在权值为负的回路。Floyd-Warshall 算法的运行时间为 Θ(V3)。

Floyd-Warshall 算法由 Robert Floyd 于 1962 年提出,但其实质上与 Bernad Roy 于 1959 年和 Stephen Warshall 于 1962 年提出的算法相同。

解决单源最短路径问题的方案有 Dijkstra 算法和 Bellman-Ford 算法,对于全源最短路径问题可以认为是单源最短路径问题(Single Source Shortest Paths Problem)的推广,即分别以每个顶点作为源顶点并求其至其它顶点的最短距离。更通用的全源最短路径算法包括:

  • 针对稠密图的 Floyd-Warshall 算法:时间复杂度为 O(V3);
  • 针对稀疏图的 Johnson 算法:时间复杂度为 O(V2logV + VE);

最短路径算法中的最优子结构指的是两顶点之间的最短路径包括路径上其它顶点的最短路径。具体描述为:对于给定的带权图 G = (V, E),设 p = <v1, v2, …,vk> 是从 v1 到 vk 的最短路径,那么对于任意 i 和 j,1 ≤ i ≤ j ≤ k,pij = <vi, vi+1, …, vj> 为 p 中顶点 vi 到 vj 的子路径,那么 pij 是顶点 vi 到 vj 的最短路径。

Floyd-Warshall 全源最短路径算法

Floyd-Warshall 算法的设计基于了如下观察。设带权图 G = (V, E) 中的所有顶点 V = {1, 2, . . . , n},考虑一个顶点子集 {1, 2, . . . , k}。对于任意对顶点 i, j,考虑从顶点 i 到 j 的所有路径的中间顶点都来自该子集 {1, 2, . . . , k},设 p 是该子集中的最短路径。Floyd-Warshall 算法描述了 p 与 i, j 间最短路径及中间顶点集合 {1, 2, . . . , k - 1} 的关系,该关系依赖于 k 是否是路径 p 上的一个中间顶点。

Floyd-Warshall 全源最短路径算法

算法伪码如下:

Floyd-Warshall 全源最短路径算法

最短路径算法的设计都使用了松弛(relaxation)技术。在算法开始时只知道图中边的权值,然后随着处理逐渐得到各对顶点的最短路径的信息,算法会逐渐更新这些信息,每步都会检查是否可以找到一条路径比当前已有路径更短,这一过程通常称为松弛(relaxation)。

C# 代码实现:

 using System;
using System.Collections.Generic;
using System.Linq; namespace GraphAlgorithmTesting
{
class Program
{
static void Main(string[] args)
{
int[,] graph = new int[, ]
{
{, , , , , , , , },
{, , , , , , , , },
{, , , , , , , , },
{, , , , , , , , },
{, , , , , , , , },
{, , , , , , , , },
{, , , , , , , , },
{, , , , , , , , },
{, , , , , , , , }
}; Graph g = new Graph(graph.GetLength());
for (int i = ; i < graph.GetLength(); i++)
{
for (int j = ; j < graph.GetLength(); j++)
{
if (graph[i, j] > )
g.AddEdge(i, j, graph[i, j]);
}
} Console.WriteLine("Graph Vertex Count : {0}", g.VertexCount);
Console.WriteLine("Graph Edge Count : {0}", g.EdgeCount);
Console.WriteLine(); int[,] distSet = g.FloydWarshell();
PrintSolution(g, distSet); // build a directed and negative weighted graph
Graph directedGraph1 = new Graph();
directedGraph1.AddEdge(, , -);
directedGraph1.AddEdge(, , );
directedGraph1.AddEdge(, , );
directedGraph1.AddEdge(, , );
directedGraph1.AddEdge(, , );
directedGraph1.AddEdge(, , );
directedGraph1.AddEdge(, , );
directedGraph1.AddEdge(, , -); Console.WriteLine();
Console.WriteLine("Graph Vertex Count : {0}", directedGraph1.VertexCount);
Console.WriteLine("Graph Edge Count : {0}", directedGraph1.EdgeCount);
Console.WriteLine(); int[,] distSet1 = directedGraph1.FloydWarshell();
PrintSolution(directedGraph1, distSet1); // build a directed and positive weighted graph
Graph directedGraph2 = new Graph();
directedGraph2.AddEdge(, , );
directedGraph2.AddEdge(, , );
directedGraph2.AddEdge(, , );
directedGraph2.AddEdge(, , ); Console.WriteLine();
Console.WriteLine("Graph Vertex Count : {0}", directedGraph2.VertexCount);
Console.WriteLine("Graph Edge Count : {0}", directedGraph2.EdgeCount);
Console.WriteLine(); int[,] distSet2 = directedGraph2.FloydWarshell();
PrintSolution(directedGraph2, distSet2); Console.ReadKey();
} private static void PrintSolution(Graph g, int[,] distSet)
{
Console.Write("\t");
for (int i = ; i < g.VertexCount; i++)
{
Console.Write(i + "\t");
}
Console.WriteLine();
Console.Write("\t");
for (int i = ; i < g.VertexCount; i++)
{
Console.Write("-" + "\t");
}
Console.WriteLine();
for (int i = ; i < g.VertexCount; i++)
{
Console.Write(i + "|\t");
for (int j = ; j < g.VertexCount; j++)
{
if (distSet[i, j] == int.MaxValue)
{
Console.Write("INF" + "\t");
}
else
{
Console.Write(distSet[i, j] + "\t");
}
}
Console.WriteLine();
}
} class Edge
{
public Edge(int begin, int end, int weight)
{
this.Begin = begin;
this.End = end;
this.Weight = weight;
} public int Begin { get; private set; }
public int End { get; private set; }
public int Weight { get; private set; } public override string ToString()
{
return string.Format(
"Begin[{0}], End[{1}], Weight[{2}]",
Begin, End, Weight);
}
} class Graph
{
private Dictionary<int, List<Edge>> _adjacentEdges
= new Dictionary<int, List<Edge>>(); public Graph(int vertexCount)
{
this.VertexCount = vertexCount;
} public int VertexCount { get; private set; } public int EdgeCount
{
get
{
return _adjacentEdges.Values.SelectMany(e => e).Count();
}
} public void AddEdge(int begin, int end, int weight)
{
if (!_adjacentEdges.ContainsKey(begin))
{
var edges = new List<Edge>();
_adjacentEdges.Add(begin, edges);
} _adjacentEdges[begin].Add(new Edge(begin, end, weight));
} public int[,] FloydWarshell()
{
/* distSet[,] will be the output matrix that will finally have the shortest
distances between every pair of vertices */
int[,] distSet = new int[VertexCount, VertexCount]; for (int i = ; i < VertexCount; i++)
{
for (int j = ; j < VertexCount; j++)
{
distSet[i, j] = int.MaxValue;
}
}
for (int i = ; i < VertexCount; i++)
{
distSet[i, i] = ;
} /* Initialize the solution matrix same as input graph matrix. Or
we can say the initial values of shortest distances are based
on shortest paths considering no intermediate vertex. */
foreach (var edge in _adjacentEdges.Values.SelectMany(e => e))
{
distSet[edge.Begin, edge.End] = edge.Weight;
} /* Add all vertices one by one to the set of intermediate vertices.
---> Before start of a iteration, we have shortest distances between all
pairs of vertices such that the shortest distances consider only the
vertices in set {0, 1, 2, .. k-1} as intermediate vertices.
---> After the end of a iteration, vertex no. k is added to the set of
intermediate vertices and the set becomes {0, 1, 2, .. k} */
for (int k = ; k < VertexCount; k++)
{
// Pick all vertices as source one by one
for (int i = ; i < VertexCount; i++)
{
// Pick all vertices as destination for the above picked source
for (int j = ; j < VertexCount; j++)
{
// If vertex k is on the shortest path from
// i to j, then update the value of distSet[i,j]
if (distSet[i, k] != int.MaxValue
&& distSet[k, j] != int.MaxValue
&& distSet[i, k] + distSet[k, j] < distSet[i, j])
{
distSet[i, j] = distSet[i, k] + distSet[k, j];
}
}
}
} return distSet;
}
}
}
}

运行结果如下:

Floyd-Warshall 全源最短路径算法

参考资料

本篇文章《Floyd-Warshall 全源最短路径算法》由 Dennis Gao 发表自博客园,未经作者本人同意禁止任何形式的转载,任何自动或人为的爬虫转载行为均为耍流氓。