/// <summary> /// 单源最短路径会把一个点到其它所有点的最短路径算出来 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="graph"></param> /// <param name="source"></param> /// <param name="weightFuc"></param> /// <returns></returns> public static bool BellmanFord <T>( this AdjacencyListGraph <T> graph, AdjacencyVertex <T> source, Func <AdjacencyListGraph <T>, AdjacencyVertex <T>, AdjacencyVertex <T>, int> weightFuc ) where T : IEquatable <T> { graph.InitializeSingleSource(source); for (int i = 1; i <= graph.VertexLenght; i++) { foreach (var edge in graph.GetEdges()) { graph.Relax(edge.Start, edge.End, weightFuc); } } foreach (var edge in graph.GetEdges()) { if (edge.Start.WeightBound > Add(edge.End.WeightBound, weightFuc(graph, edge.Start, edge.End))) { return(false); } } return(true); }
/// <summary> /// 有向无回路图 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="graph"></param> /// <param name="source"></param> /// <param name="weightFuc"></param> /// <returns></returns> public static void DAGShortestPath <T>( this AdjacencyListGraph <T> graph, AdjacencyVertex <T> source, Func <AdjacencyListGraph <T>, AdjacencyVertex <T>, AdjacencyVertex <T>, int> weightFuc ) where T : IEquatable <T> { graph.TopologicalSort(); graph.InitializeSingleSource(source); var vertexs = graph.GetVertexs(); foreach (var orderVertex in vertexs) { var edges = graph.GetVertexEdge(orderVertex); foreach (var edge in edges) { graph.Relax(edge.Start, edge.End, weightFuc); } } }