public List <UndirEdge> FindPath(string start, string end) { var dijkstra = new UndirectedDijkstraShortestPathAlgorithm <string, UndirEdge>(this, edge => 1); var observer = new UndirectedVertexPredecessorRecorderObserver <string, UndirEdge>(); observer.Attach(dijkstra); var nodeCheckX = Vertices.FirstOrDefault(node => node == start); var nodeCheckY = Vertices.FirstOrDefault(node => node == end); if (nodeCheckX != null && nodeCheckY != null) { dijkstra.Compute(start); IEnumerable <UndirEdge> path = null; try { observer.TryGetPath(end, out path); } catch { } return(path.ToList()); } else { return(null); } }
public void TryGetDistance_Throws() { var graph = new UndirectedGraph <TestVertex, Edge <TestVertex> >(); var algorithm = new UndirectedDijkstraShortestPathAlgorithm <TestVertex, Edge <TestVertex> >(graph, edge => 1.0); TryGetDistance_Throws_Test(algorithm); }
public void ClearRootVertex() { var graph = new UndirectedGraph <int, Edge <int> >(); var algorithm = new UndirectedDijkstraShortestPathAlgorithm <int, Edge <int> >(graph, edge => 1.0); ClearRootVertex_Test(algorithm); }
public void FindShortestPathForSimpleUndirectedGraphUsingDijkstraAlgorithm() { var graph = new UndirectedGraph <object, Edge <object> >(true); object v1 = "vertex1"; object v2 = "vertex2"; object v3 = "vertex3"; var e1 = new Edge <object>(v1, v2); var e2 = new Edge <object>(v2, v3); var e3 = new Edge <object>(v3, v1); graph.AddVertex(v1); graph.AddVertex(v2); graph.AddVertex(v3); graph.AddEdge(e1); graph.AddEdge(e2); graph.AddEdge(e3); var algorithm = new UndirectedDijkstraShortestPathAlgorithm <object, Edge <object> >(graph, edge => (double)1); var observer = new UndirectedVertexPredecessorRecorderObserver <object, Edge <object> >(); using (observer.Attach(algorithm)) { algorithm.Compute(v1); } IEnumerable <Edge <object> > path; observer.TryGetPath(v3, out path); foreach (var edge in path) { Console.WriteLine(edge); } }
public void UndirectedDijkstraSimpleGraph() { var undirectedGraph = new UndirectedGraph <object, Edge <object> >(true); object v1 = "vertex1"; object v2 = "vertex2"; object v3 = "vertex3"; var e1 = new Edge <object>(v1, v2); var e2 = new Edge <object>(v2, v3); var e3 = new Edge <object>(v3, v1); undirectedGraph.AddVertex(v1); undirectedGraph.AddVertex(v2); undirectedGraph.AddVertex(v3); undirectedGraph.AddEdge(e1); undirectedGraph.AddEdge(e2); undirectedGraph.AddEdge(e3); var algorithm = new UndirectedDijkstraShortestPathAlgorithm <object, Edge <object> >( undirectedGraph, edge => 1.0); var observer = new UndirectedVertexPredecessorRecorderObserver <object, Edge <object> >(); using (observer.Attach(algorithm)) algorithm.Compute(v1); Assert.IsTrue(observer.TryGetPath(v3, out _)); }
public void FindShortestPathForSimpleUndirectedGraphUsingDijkstraAlgorithm() { var graph = new UndirectedGraph<object, Edge<object>>(true); object v1 = "vertex1"; object v2 = "vertex2"; object v3 = "vertex3"; var e1 = new Edge<object>(v1, v2); var e2 = new Edge<object>(v2, v3); var e3 = new Edge<object>(v3, v1); graph.AddVertex(v1); graph.AddVertex(v2); graph.AddVertex(v3); graph.AddEdge(e1); graph.AddEdge(e2); graph.AddEdge(e3); var algorithm = new UndirectedDijkstraShortestPathAlgorithm<object, Edge<object>>(graph, edge => (double)1); var observer = new UndirectedVertexPredecessorRecorderObserver<object, Edge<object>>(); using (observer.Attach(algorithm)) { algorithm.Compute(v1); } IEnumerable<Edge<object>> path; observer.TryGetPath(v3, out path); foreach (var edge in path) { Console.WriteLine(edge); } }
private Dictionary <MapNode, double> GetWeightedMapNodeDistances(Board board, MapNode source, AllianceScenario allianceScenario) { Unit unit = board.OccupiedMapNodes[source]; TerritoryStrengths territoryStrengths = new TerritoryStrengths(); territoryStrengths.Init(board); Func <UndirectedEdge <MapNode>, double> WeightFunction = (edge) => { double powerCount = territoryStrengths.GetPowerCount(edge.Target.Territory, unit.Power); double totalAnimosity = allianceScenario.OutEdges(unit.Power) .Where(e => territoryStrengths.GetStrength(edge.Target.Territory, e.Target) > 0) .Sum(e => e.Animosity); return(1 + (powerCount - totalAnimosity)); }; var alg = new UndirectedDijkstraShortestPathAlgorithm <MapNode, UndirectedEdge <MapNode> >(unit.MyMap, WeightFunction); alg.SetRootVertex(source); _predecessorObserver.VertexPredecessors.Clear(); using (var foo = _predecessorObserver.Attach(alg)) { alg.Compute(); } return(alg.Distances); }
/// <summary> /// Computes the minimum spanning tree using Prim's algorithm. /// Prim's algorithm is simply implemented by calling Dijkstra shortest path. /// </summary> /// <typeparam name="TVertex">type of the vertices</typeparam> /// <typeparam name="TEdge">type of the edges</typeparam> /// <param name="visitedGraph"></param> /// <param name="weights"></param> /// <returns></returns> public static IEnumerable <TEdge> MinimumSpanningTreePrim <TVertex, TEdge>( #if !NET20 this #endif IUndirectedGraph <TVertex, TEdge> visitedGraph, Func <TEdge, double> weights) where TEdge : IEdge <TVertex> { Contract.Requires(visitedGraph != null); Contract.Requires(weights != null); if (visitedGraph.VertexCount == 0) { return(new TEdge[0]); } var distanceRelaxer = PrimRelaxer.Instance; var dijkstra = new UndirectedDijkstraShortestPathAlgorithm <TVertex, TEdge>(visitedGraph, weights, distanceRelaxer); var edgeRecorder = new UndirectedVertexPredecessorRecorderObserver <TVertex, TEdge>(); using (edgeRecorder.Attach(dijkstra)) dijkstra.Compute(); return(edgeRecorder.VertexPredecessors.Values); }
public void SetRootVertex_Throws() { var graph = new UndirectedGraph <TestVertex, Edge <TestVertex> >(); var algorithm = new UndirectedDijkstraShortestPathAlgorithm <TestVertex, Edge <TestVertex> >(graph, _ => 1.0); SetRootVertex_Throws_Test(algorithm); }
public static TryFunc <TVertex, IEnumerable <TEdge> > ShortestPathsDijkstra <TVertex, TEdge>( #if !NET20 this #endif IUndirectedGraph <TVertex, TEdge> visitedGraph, Func <TEdge, double> edgeWeights, TVertex source ) where TEdge : IEdge <TVertex> { Contract.Requires(visitedGraph != null); Contract.Requires(edgeWeights != null); Contract.Requires(source != null); var algorithm = new UndirectedDijkstraShortestPathAlgorithm <TVertex, TEdge>(visitedGraph, edgeWeights); var predecessorRecorder = new UndirectedVertexPredecessorRecorderObserver <TVertex, TEdge>(); using (predecessorRecorder.Attach(algorithm)) algorithm.Compute(source); var predecessors = predecessorRecorder.VertexPredecessors; return(delegate(TVertex v, out IEnumerable <TEdge> edges) { return EdgeExtensions.TryGetPath(predecessors, v, out edges); }); }
public static IDictionary <string, double> Get(IUndirectedGraph <string, TaggedEdge <string, string> > graph, string root) { Func <TaggedEdge <string, string>, double> Weights = e => double.Parse(e.Tag); var algorithm = new UndirectedDijkstraShortestPathAlgorithm <string, TaggedEdge <string, string> >(graph, Weights); algorithm.Compute(root); return(algorithm.Distances); }
public static IDictionary <int, double> Get(IUndirectedGraph <int, Edge <int> > graph, int root) { Func <Edge <int>, double> Weights = e => 1.0; var algorithm = new UndirectedDijkstraShortestPathAlgorithm <int, Edge <int> >(graph, Weights); algorithm.Compute(root); return(algorithm.Distances); }
public void ComputeWithRoot() { var graph = new UndirectedGraph <int, Edge <int> >(); graph.AddVertex(0); var algorithm = new UndirectedDijkstraShortestPathAlgorithm <int, Edge <int> >(graph, edge => 1.0); ComputeWithRoot_Test(algorithm); }
public void TryGetDistance() { var graph = new UndirectedGraph <int, Edge <int> >(); graph.AddVertex(1); var algorithm = new UndirectedDijkstraShortestPathAlgorithm <int, Edge <int> >(graph, edge => 1.0); TryGetDistance_Test(algorithm); }
private void GetDistancesAndWeights(out double[,] d, out double[,] w) { d = new double[VisitedGraph.VertexCount, VisitedGraph.VertexCount]; w = new double[VisitedGraph.VertexCount, VisitedGraph.VertexCount]; double maxCost = 0.0001; var undirected = new UndirectedBidirectionalGraph <TVertex, TEdge>(VisitedGraph); int i = 0; foreach (TVertex source in undirected.Vertices) { var spa = new UndirectedDijkstraShortestPathAlgorithm <TVertex, TEdge>(undirected, edge => edge is IWeightedEdge <TVertex>?Parameters.WeightAdjustment - (((IWeightedEdge <TVertex>)edge).Weight) : 1.0); spa.Compute(source); int j = 0; foreach (TVertex target in undirected.Vertices) { double cost; if (spa.TryGetDistance(target, out cost)) { d[i, j] = cost; if (cost > maxCost) { maxCost = cost; } } else { d[i, j] = double.NaN; } j++; } i++; } double idealEdgeLength = (Math.Min(Parameters.Width, Parameters.Height) / maxCost) * Parameters.LengthFactor; double disconnectedCost = maxCost * Parameters.DisconnectedMultiplier; for (i = 0; i < VisitedGraph.VertexCount; i++) { for (int j = 0; j < VisitedGraph.VertexCount; j++) { if (double.IsNaN(d[i, j])) { d[i, j] = disconnectedCost; } else { d[i, j] *= idealEdgeLength; } w[i, j] = Math.Pow(Math.Max(d[i, j], 0.0001), -Parameters.Alpha); } } }
private static IList <Edge> ComputeShortestPath(Edge branch, IEnumerable <Edge> delaunyEdges, Matrix volumeIndexToNormalizedVolumeCoordinates) { var graph = new UndirectedGraph <Vector3, Edge <Vector3> >(); foreach (var delaunyEdge in delaunyEdges) { graph.AddVerticesAndEdge(new Edge <Vector3>(delaunyEdge.P1, delaunyEdge.P2)); } var dijkstraShortestPathAlgorithm = new UndirectedDijkstraShortestPathAlgorithm <Vector3, Edge <Vector3> >(graph, edge => CalculateEdgeWeights(edge, volumeIndexToNormalizedVolumeCoordinates)); var visitor = new UndirectedVertexPredecessorRecorderObserver <Vector3, Edge <Vector3> >(); using (visitor.Attach(dijkstraShortestPathAlgorithm)) { dijkstraShortestPathAlgorithm.Compute(branch.P1); } IEnumerable <Edge <Vector3> > shortestPath; visitor.TryGetPath(branch.P2, out shortestPath); var edgeList = (from edge in shortestPath select new Edge { P1 = edge.Source, P2 = edge.Target }).ToList(); var orientedEdgeList = new List <Edge>(); var edgeListP1 = edgeList[0].P1; var edgeListP2 = edgeList[0].P2; orientedEdgeList.Add(!edgeList[0].P1.Equals(branch.P1) ? new Edge { P1 = edgeListP2, P2 = edgeListP1 } : new Edge { P1 = edgeListP1, P2 = edgeListP2 }); for (int i = 1; i < edgeList.Count; i++) { edgeListP1 = edgeList[i].P1; edgeListP2 = edgeList[i].P2; orientedEdgeList.Add(!edgeList[i].P1.Equals(orientedEdgeList[i - 1].P2) ? new Edge { P1 = edgeListP2, P2 = edgeListP1 } : new Edge { P1 = edgeListP1, P2 = edgeListP2 }); } return(orientedEdgeList); }
public void GetVertexColor_Throws() { var graph = new UndirectedGraph <int, Edge <int> >(); graph.AddVertex(0); var algorithm = new UndirectedDijkstraShortestPathAlgorithm <int, Edge <int> >(graph, edge => 1.0); algorithm.Compute(0); // ReSharper disable once ReturnValueOfPureMethodIsNotUsed Assert.Throws <VertexNotFoundException>(() => algorithm.GetVertexColor(1)); }
public void GetVertexColor() { var graph = new UndirectedGraph <int, Edge <int> >(); graph.AddVerticesAndEdge(new Edge <int>(1, 2)); var algorithm = new UndirectedDijkstraShortestPathAlgorithm <int, Edge <int> >(graph, edge => 1.0); algorithm.Compute(1); Assert.AreEqual(GraphColor.Black, algorithm.GetVertexColor(1)); Assert.AreEqual(GraphColor.Black, algorithm.GetVertexColor(2)); }
/// <param name="g">The graph.</param> /// <returns>Returns with the distance between the vertices (distance: number of the edges).</returns> public static double[,] GetDistances <Vertex, Edge, Graph>(Graph g) where Edge : IEdge <Vertex> where Graph : IBidirectionalGraph <Vertex, Edge> { var distances = new double[g.VertexCount, g.VertexCount]; for (int k = 0; k < g.VertexCount; k++) { for (int j = 0; j < g.VertexCount; j++) { distances[k, j] = double.PositiveInfinity; } } var undirected = new UndirectedBidirectionalGraph <Vertex, Edge>(g); //minden élet egy hosszal veszünk figyelembe - unweighted var weights = new Dictionary <Edge, double>(); foreach (Edge edge in undirected.Edges) { weights[edge] = 1; } //compute the distances from every vertex: O(n(n^2 + e)) complexity int i = 0; foreach (Vertex source in g.Vertices) { //compute the distances from the 'source' var spaDijkstra = new UndirectedDijkstraShortestPathAlgorithm <Vertex, Edge>(undirected, (edge) => weights[edge], DistanceRelaxers.ShortestDistance); spaDijkstra.Compute(source); int j = 0; foreach (Vertex v in undirected.Vertices) { double d = spaDijkstra.Distances[v]; distances[i, j] = Math.Min(distances[i, j], d); distances[i, j] = Math.Min(distances[i, j], distances[j, i]); distances[j, i] = Math.Min(distances[i, j], distances[j, i]); j++; } i++; } return(distances); }
public static double[,] GetDistances <TVertex, TEdge, TGraph>( [NotNull] this TGraph graph) where TEdge : IEdge <TVertex> where TGraph : IBidirectionalGraph <TVertex, TEdge> { if (graph == null) { throw new ArgumentNullException(nameof(graph)); } var distances = new double[graph.VertexCount, graph.VertexCount]; for (int k = 0; k < graph.VertexCount; ++k) { for (int j = 0; j < graph.VertexCount; ++j) { distances[k, j] = double.PositiveInfinity; } } var undirected = new UndirectedBidirectionalGraph <TVertex, TEdge>(graph); // Compute the distances from every vertex: O(n(n^2 + e)) complexity int i = 0; foreach (TVertex source in graph.Vertices) { // Compute the distances from the 'source' // Each edge is taken into account as 1 (unweighted) var dijkstra = new UndirectedDijkstraShortestPathAlgorithm <TVertex, TEdge>( undirected, edge => 1.0, DistanceRelaxers.ShortestDistance); dijkstra.Compute(source); int j = 0; foreach (TVertex vertex in undirected.Vertices) { double distance = dijkstra.Distances[vertex]; distances[i, j] = Math.Min(distances[i, j], distance); distances[i, j] = Math.Min(distances[i, j], distances[j, i]); distances[j, i] = Math.Min(distances[i, j], distances[j, i]); ++j; } ++i; } return(distances); }
public void Constructor() { Func <Edge <int>, double> Weights = e => 1.0; var graph = new UndirectedGraph <int, Edge <int> >(); var algorithm = new UndirectedDijkstraShortestPathAlgorithm <int, Edge <int> >(graph, Weights); AssertAlgorithmProperties(algorithm, graph, Weights); algorithm = new UndirectedDijkstraShortestPathAlgorithm <int, Edge <int> >(graph, Weights, DistanceRelaxers.CriticalDistance); AssertAlgorithmProperties(algorithm, graph, Weights, DistanceRelaxers.CriticalDistance); algorithm = new UndirectedDijkstraShortestPathAlgorithm <int, Edge <int> >(null, graph, Weights, DistanceRelaxers.CriticalDistance); AssertAlgorithmProperties(algorithm, graph, Weights, DistanceRelaxers.CriticalDistance); #region Local function void AssertAlgorithmProperties <TVertex, TEdge>( UndirectedDijkstraShortestPathAlgorithm <TVertex, TEdge> algo, IUndirectedGraph <TVertex, TEdge> g, Func <TEdge, double> eWeights = null, IDistanceRelaxer relaxer = null) where TEdge : IEdge <TVertex> { AssertAlgorithmState(algo, g); Assert.IsNull(algo.VerticesColors); if (eWeights is null) { Assert.IsNotNull(algo.Weights); } else { Assert.AreSame(eWeights, algo.Weights); } Assert.IsNull(algo.Distances); if (relaxer is null) { Assert.IsNotNull(algo.DistanceRelaxer); } else { Assert.AreSame(relaxer, algo.DistanceRelaxer); } } #endregion }
/// <param name="g">The graph.</param> /// <returns>Returns with the distance between the vertices (distance: number of the edges).</returns> private static double[,] GetDistances <TVertex, TEdge, TGraph>(TGraph g) where TEdge : IEdge <TVertex> where TGraph : IBidirectionalGraph <TVertex, TEdge> { var distances = new double[g.VertexCount, g.VertexCount]; for (var k = 0; k < g.VertexCount; k++) { for (var j = 0; j < g.VertexCount; j++) { distances[k, j] = double.PositiveInfinity; } } var undirected = new UndirectedBidirectionalGraph <TVertex, TEdge>(g); //minden йlet egy hosszal veszьnk figyelembe - unweighted var weights = new Dictionary <TEdge, double>(); foreach (var edge in undirected.Edges) { weights[edge] = 1; } //compute the distances from every vertex: O(n(n^2 + e)) complexity var i = 0; foreach (var source in g.Vertices) { //compute the distances from the 'source' var spaDijkstra = new UndirectedDijkstraShortestPathAlgorithm <TVertex, TEdge>(undirected, edge => weights[edge], QuickGraph.Algorithms.DistanceRelaxers.ShortestDistance); spaDijkstra.Compute(source); var j = 0; foreach (var v in undirected.Vertices) { var d = spaDijkstra.Distances[v]; distances[i, j] = Math.Min(distances[i, j], d); distances[i, j] = Math.Min(distances[i, j], distances[j, i]); distances[j, i] = Math.Min(distances[i, j], distances[j, i]); j++; } i++; } return(distances); }
public static UndirectedDijkstraShortestPathAlgorithm <int, Edge <int> > CreateAlgorithmAndMaybeDoComputation( [NotNull] ContractScenario scenario) { var graph = new UndirectedGraph <int, Edge <int> >(); graph.AddVerticesAndEdgeRange(scenario.EdgesInGraph.Select(e => new Edge <int>(e.Source, e.Target))); graph.AddVertexRange(scenario.SingleVerticesInGraph); double Weights(Edge <int> e) => 1.0; var algorithm = new UndirectedDijkstraShortestPathAlgorithm <int, Edge <int> >(graph, Weights); if (scenario.DoComputation) { algorithm.Compute(scenario.Root); } return(algorithm); }
private static void RunUndirectedDijkstraAndCheck <TVertex, TEdge>([NotNull] IUndirectedGraph <TVertex, TEdge> graph, [NotNull] TVertex root) where TEdge : IEdge <TVertex> { var distances = new Dictionary <TEdge, double>(); foreach (TEdge edge in graph.Edges) { distances[edge] = graph.AdjacentDegree(edge.Source) + 1; } var algorithm = new UndirectedDijkstraShortestPathAlgorithm <TVertex, TEdge>(graph, e => distances[e]); var predecessors = new UndirectedVertexPredecessorRecorderObserver <TVertex, TEdge>(); using (predecessors.Attach(algorithm)) algorithm.Compute(root); Verify(algorithm, predecessors); }
private static IEnumerable <UnitMove> GetConvoyMoves(Board board) { List <UnitMove> convoyMoves = new List <UnitMove>(); var currentConvoyMap = board.GetCurrentConvoyMap(); foreach (MapNode source in currentConvoyMap.Vertices.Where(mn => mn.Territory.TerritoryType == TerritoryType.Coast)) { Unit unit; if (!board.OccupiedMapNodes.TryGetValue(source.ConvoyParent(), out unit)) { continue; } if (currentConvoyMap.AdjacentDegree(source) > 0) { //var alg = new HoffmanPavleyRankedShortestPathAlgorithm<MapNode, UndirectedEdge<MapNode>>( currentConvoyMap, n => 1); var alg = new UndirectedDijkstraShortestPathAlgorithm <MapNode, UndirectedEdge <MapNode> >(currentConvoyMap, n => 1); //alg.SetGoalVertex(target); var predecessorObserver = new UndirectedVertexPredecessorRecorderObserver <MapNode, UndirectedEdge <MapNode> >(); alg.SetRootVertex(source); using (var foo = predecessorObserver.Attach(alg)) { alg.Compute(); } foreach (MapNode target in currentConvoyMap.Vertices.Where(mn => mn.Territory.TerritoryType == TerritoryType.Coast)) { IEnumerable <UndirectedEdge <MapNode> > rawPath; if (!predecessorObserver.TryGetPath(target, out rawPath)) { continue; } List <MapNode> edgeList = MakeConvoyPathList(source, target, rawPath); var convoyMove = new UnitMove(unit, new UndirectedEdge <MapNode>(source.ConvoyParent(), target.ConvoyParent()), edgeList); convoyMoves.Add(convoyMove); } } } return(convoyMoves); }
private static void Verify <TVertex, TEdge>( [NotNull] UndirectedDijkstraShortestPathAlgorithm <TVertex, TEdge> algorithm, [NotNull] UndirectedVertexPredecessorRecorderObserver <TVertex, TEdge> predecessors) where TEdge : IEdge <TVertex> { // Verify the result foreach (TVertex vertex in algorithm.VisitedGraph.Vertices) { if (!predecessors.VerticesPredecessors.TryGetValue(vertex, out TEdge predecessor)) { continue; } if (predecessor.Source.Equals(vertex)) { continue; } Assert.AreEqual( algorithm.TryGetDistance(vertex, out double currentDistance), algorithm.TryGetDistance(predecessor.Source, out double predecessorDistance)); Assert.GreaterOrEqual(currentDistance, predecessorDistance); } }
private static void RunUndirectedDijkstraAndCheck <TVertex, TEdge>([NotNull] IUndirectedGraph <TVertex, TEdge> graph, [NotNull] TVertex root) where TEdge : IEdge <TVertex> { var distances = new Dictionary <TEdge, double>(); foreach (TEdge edge in graph.Edges) { distances[edge] = graph.AdjacentDegree(edge.Source) + 1; } var algorithm = new UndirectedDijkstraShortestPathAlgorithm <TVertex, TEdge>(graph, e => distances[e]); var predecessors = new UndirectedVertexPredecessorRecorderObserver <TVertex, TEdge>(); using (predecessors.Attach(algorithm)) algorithm.Compute(root); algorithm.InitializeVertex += vertex => { Assert.AreEqual(GraphColor.White, algorithm.VerticesColors[vertex]); }; algorithm.DiscoverVertex += vertex => { Assert.AreEqual(GraphColor.Gray, algorithm.VerticesColors[vertex]); }; algorithm.FinishVertex += vertex => { Assert.AreEqual(GraphColor.Black, algorithm.VerticesColors[vertex]); }; Assert.IsNotNull(algorithm.Distances); Assert.AreEqual(graph.VertexCount, algorithm.Distances.Count); Verify(algorithm, predecessors); }
private static void Verify <TVertex, TEdge>( [NotNull] UndirectedDijkstraShortestPathAlgorithm <TVertex, TEdge> algorithm, [NotNull] UndirectedVertexPredecessorRecorderObserver <TVertex, TEdge> predecessors) where TEdge : IEdge <TVertex> { // Verify the result foreach (TVertex vertex in algorithm.VisitedGraph.Vertices) { if (!predecessors.VertexPredecessors.TryGetValue(vertex, out TEdge predecessor)) { continue; } if (predecessor.Source.Equals(vertex)) { continue; } bool found = algorithm.TryGetDistance(vertex, out double vd); Assert.AreEqual(found, algorithm.TryGetDistance(predecessor.Source, out double vp)); if (found) { Assert.AreEqual(vd, vp + 1); } } }
public static void createTables() { // Create graph var graph = new UndirectedGraph <int, Edge <int> >(); // Add vertices to the graph for (var i = 0; i < FormMain.nodes.Count; i++) { graph.AddVertex(i); } // Create edges var edgeCost = new Dictionary <Edge <int>, double>(); for (var i = 0; i < FormMain.edges.Count; i++) { var quickGraphEdge = new Edge <int>(FormMain.nodes.IndexOf(FormMain.edges[i].nodes[0]), FormMain.nodes.IndexOf(FormMain.edges[i].nodes[1])); graph.AddEdge(quickGraphEdge); edgeCost.Add(quickGraphEdge, FormMain.edges[i].Weight); } // Initialize tables distanceTable = new double[FormMain.nodes.Count, FormMain.nodes.Count]; pathTable = new List <int> [FormMain.nodes.Count, FormMain.nodes.Count]; for (var i = 0; i < FormMain.nodes.Count; i++) { for (var j = 0; j < FormMain.nodes.Count; j++) { distanceTable[i, j] = double.PositiveInfinity; pathTable[i, j] = new List <int>(); } } // Create tables for (var source = 0; source < FormMain.nodes.Count; source++) { // We want to use Dijkstra on this graph var dijkstra = new UndirectedDijkstraShortestPathAlgorithm <int, Edge <int> >(graph, edge => edgeCost[edge]); // attach a distance observer to give us the shortest path distances var distObserver = new UndirectedVertexDistanceRecorderObserver <int, Edge <int> >(edge => edgeCost[edge]); distObserver.Attach(dijkstra); // Attach a Vertex Predecessor Recorder Observer to give us the paths var predecessorObserver = new UndirectedVertexPredecessorRecorderObserver <int, Edge <int> >(); predecessorObserver.Attach(dijkstra); // Run the algorithm for current Node dijkstra.Compute(source); // Add values to table foreach (var target in distObserver.Distances) { distanceTable[source, target.Key] = target.Value; IEnumerable <Edge <int> > path; if (predecessorObserver.TryGetPath(target.Key, out path)) { pathTable[source, target.Key].AddRange(path.Select(edge => edge.Source).Concat(path.Select(edge => edge.Target)).Distinct().OrderBy(next => distObserver.Distances[next])); } } } // Create route tables foreach (var source in FormMain.nodes) { source.routeTable = FormMain.nodes.ToDictionary(target => target, target => ( from edge in FormMain.edges where edge.nodes.Contains(source) let adjacent = edge.nodes[0] != source ? edge.nodes[0] : edge.nodes[1] where !pathTable[adjacent.ID, target.ID].Contains(source.ID) orderby edge.Weight + distanceTable[adjacent.ID, target.ID] ascending select adjacent ).ToList()); } TablesRequired = false; }
/// <summary> /// Compute /// </summary> private void Form_Load(object sender, EventArgs e) { // Crete distance table tableDijkstra.Columns.Add(); tableDijkstra.Rows.Add(tableDijkstra.NewRow()); for (var i = 0; i < FormMain.nodes.Count; i++) { tableDijkstra.Columns.Add(); tableDijkstra.Rows.Add(tableDijkstra.NewRow()); tableDijkstra.Rows[0][i + 1] = tableDijkstra.Rows[i + 1][0] = i; } // Create graph var graph = new UndirectedGraph <int, Edge <int> >(); // Add vertices to the graph for (var i = 0; i < FormMain.nodes.Count; i++) { graph.AddVertex(i); } // Create edges for (var i = 0; i < FormMain.edges.Count; i++) { var quickGraphEdge = new Edge <int>(FormMain.nodes.IndexOf(FormMain.edges[i].nodes[0]), FormMain.nodes.IndexOf(FormMain.edges[i].nodes[1])); graph.AddEdge(quickGraphEdge); } // Compute distances for (var source = 0; source < FormMain.nodes.Count; source++) { // We want to use Dijkstra on this graph var dijkstra = new UndirectedDijkstraShortestPathAlgorithm <int, Edge <int> >(graph, edge => 1); // attach a distance observer to give us the shortest path distances var distObserver = new UndirectedVertexDistanceRecorderObserver <int, Edge <int> >(edge => 1); distObserver.Attach(dijkstra); // Attach a Vertex Predecessor Recorder Observer to give us the paths var predecessorObserver = new UndirectedVertexPredecessorRecorderObserver <int, Edge <int> >(); predecessorObserver.Attach(dijkstra); // Run the algorithm for current Node dijkstra.Compute(source); // Show distances foreach (var target in distObserver.Distances) { tableDijkstra.Rows[source + 1][target.Key + 1] = target.Value.ToString(); IEnumerable <Edge <int> > edgePath; if (predecessorObserver.TryGetPath(target.Key, out edgePath)) { string str = " ("; foreach (var nodeID in edgePath.Select(edge => edge.Source).Concat(edgePath.Select(edge => edge.Target)).Distinct().OrderBy(next => distObserver.Distances[next])) { str += string.Format("{0}->", nodeID); } tableDijkstra.Rows[source + 1][target.Key + 1] += str.Substring(0, str.Length - 2) + ")"; } } } dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader; }
public static void createTables() { // Create graph var graph = new UndirectedGraph<int, Edge<int>>(); // Add vertices to the graph for (var i = 0; i < FormMain.nodes.Count; i++) graph.AddVertex(i); // Create edges var edgeCost = new Dictionary<Edge<int>, double>(); for (var i = 0; i < FormMain.edges.Count; i++) { var quickGraphEdge = new Edge<int>(FormMain.nodes.IndexOf(FormMain.edges[i].nodes[0]), FormMain.nodes.IndexOf(FormMain.edges[i].nodes[1])); graph.AddEdge(quickGraphEdge); edgeCost.Add(quickGraphEdge, FormMain.edges[i].Weight); } // Initialize tables distanceTable = new double[FormMain.nodes.Count, FormMain.nodes.Count]; pathTable = new List<int>[FormMain.nodes.Count, FormMain.nodes.Count]; for (var i = 0; i < FormMain.nodes.Count; i++) for (var j = 0; j < FormMain.nodes.Count; j++) { distanceTable[i, j] = double.PositiveInfinity; pathTable[i, j] = new List<int>(); } // Create tables for (var source = 0; source < FormMain.nodes.Count; source++) { // We want to use Dijkstra on this graph var dijkstra = new UndirectedDijkstraShortestPathAlgorithm<int, Edge<int>>(graph, edge => edgeCost[edge]); // attach a distance observer to give us the shortest path distances var distObserver = new UndirectedVertexDistanceRecorderObserver<int, Edge<int>>(edge => edgeCost[edge]); distObserver.Attach(dijkstra); // Attach a Vertex Predecessor Recorder Observer to give us the paths var predecessorObserver = new UndirectedVertexPredecessorRecorderObserver<int, Edge<int>>(); predecessorObserver.Attach(dijkstra); // Run the algorithm for current Node dijkstra.Compute(source); // Add values to table foreach (var target in distObserver.Distances) { distanceTable[source, target.Key] = target.Value; IEnumerable<Edge<int>> path; if (predecessorObserver.TryGetPath(target.Key, out path)) pathTable[source, target.Key].AddRange(path.Select(edge => edge.Source).Concat(path.Select(edge => edge.Target)).Distinct().OrderBy(next => distObserver.Distances[next])); } } // Create route tables foreach (var source in FormMain.nodes) source.routeTable = FormMain.nodes.ToDictionary(target => target, target => ( from edge in FormMain.edges where edge.nodes.Contains(source) let adjacent = edge.nodes[0] != source ? edge.nodes[0] : edge.nodes[1] where !pathTable[adjacent.ID, target.ID].Contains(source.ID) orderby edge.Weight + distanceTable[adjacent.ID, target.ID] ascending select adjacent ).ToList()); TablesRequired = false; }
public static string ShortestWayDijsktraAlgorithmUnDirected(GraphVertex vertexD, List <GraphEdge> listEdge, List <GraphVertex> listVertex) { string s = ""; UndirectedGraph <GraphVertex, UndirectedEdge <GraphVertex> > graph = new UndirectedGraph <GraphVertex, UndirectedEdge <GraphVertex> >(); foreach (var vert in listVertex) { graph.AddVertex(vert); } foreach (var edge in listEdge) { graph.AddEdge(new UndirectedEdge <GraphVertex>(edge.StartVertex, edge.EndVertex)); } Dictionary <UndirectedEdge <GraphVertex>, double> edgeCost = new Dictionary <UndirectedEdge <GraphVertex>, double>(); int i = 0; foreach (var edge in graph.Edges) { double eCost = EdgeCostSearching(edge.Source, edge.Target, listEdge); edgeCost.Add(edge, eCost); i++; } IEnumerable <UndirectedEdge <GraphVertex> > pathh; Func <UndirectedEdge <GraphVertex>, double> getW = edge => edgeCost[edge]; UndirectedDijkstraShortestPathAlgorithm <GraphVertex, UndirectedEdge <GraphVertex> > diijkstra = new UndirectedDijkstraShortestPathAlgorithm <GraphVertex, UndirectedEdge <GraphVertex> >(graph, getW); UndirectedVertexDistanceRecorderObserver <GraphVertex, UndirectedEdge <GraphVertex> > distObs = new UndirectedVertexDistanceRecorderObserver <GraphVertex, UndirectedEdge <GraphVertex> >(getW); using (distObs.Attach(diijkstra)) { UndirectedVertexPredecessorRecorderObserver <GraphVertex, UndirectedEdge <GraphVertex> > predObs = new UndirectedVertexPredecessorRecorderObserver <GraphVertex, UndirectedEdge <GraphVertex> >(); using (predObs.Attach(diijkstra)) { diijkstra.Compute(vertexD); foreach (KeyValuePair <GraphVertex, double> kvp in distObs.Distances) { s += "From " + vertexD.Name + " to " + kvp.Key.Name + " is " + kvp.Value + " by "; if (predObs.TryGetPath(kvp.Key, out pathh)) { foreach (var t in pathh) { s += "edge " + t.Source.Name + "<->" + t.Target.Name + " "; } } s += System.Environment.NewLine; } } } return(s); }