Here is an example of my problem.
I would like to code this in C# in such a way so that I may interrogate the structure and find information such as:
So I thought I would use an Adjacency List to model my graph, but then I thought this is a common thing, and started looking for libraries to help quicken the process (no need to re-invent the wheel .. etc.)
I came across this Library that was recommended a couple of time on various topics, but I am finding it real hard modelling my drawn graph above.
A possible solution is to model your graph as an AdjacencyGraph<string, Edge<string>>
and construct a Dictionary<Edge<string>, double>
cost dictionary, where 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);
}
Your _graph
is now:
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. It prints:
Path found from A to E: A > D > B > E
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With