Weighted Graphics Index in QuickGraph Library

Here is an example of my problem.

enter image description here

I would like to code this in C # so that I can query the structure and find information such as:

  • The total distance from A to B.
  • The smallest distance from A to E (saving you cannot go against the direction of the arrow).

So, I thought that I would use the Adjacency list to simulate my schedule, but then I thought it was a normal thing and started looking for libraries to speed up the process (there is no need to reinvent the wheel, etc.). )

I stumbled upon this library , which was recommended a couple of times on various topics, but I find this a real hard simulation of my drawn graphics above.

+6
source share
1 answer

A possible solution is to simulate your chart as AdjacencyGraph<string, Edge<string>> and build a dictionary of values Dictionary<Edge<string>, double> , where the costs are your distances.

 // ... private AdjacencyGraph<string, Edge<string>> _graph; private Dictionary<Edge<string>, double> _costs; public void SetUpEdgesAndCosts() { _graph = new AdjacencyGraph<string, Edge<string>>(); _costs = new Dictionary<Edge<string>, double>(); AddEdgeWithCosts("A", "D", 4.0); // snip AddEdgeWithCosts("C", "B", 1.0); } private void AddEdgeWithCosts(string source, string target, double cost) { var edge = new Edge<string>(source, target); _graph.AddVerticesAndEdge(edge); _costs.Add(edge, cost); } 

Now your _graph :

your graph

Then you can find the shortest path from A to E using:

 private void PrintShortestPath(string @from, string to) { var edgeCost = AlgorithmExtensions.GetIndexer(_costs); var tryGetPath = _graph.ShortestPathsDijkstra(edgeCost, @from); IEnumerable<Edge<string>> path; if (tryGetPath(to, out path)) { PrintPath(@from, to, path); } else { Console.WriteLine("No path found from {0} to {1}."); } } 

This is adapted from the QuickGraph wiki . He prints:

 Path found from A to E: A > D > B > E 
+7
source

Source: https://habr.com/ru/post/952627/


All Articles