private void GetShortestGraph(DirectedGraphNode sourceNode, DirectedGraphNode targetNode, DirectedGraph graph) { if (sourceNode.Name == targetNode.Name) { return; } var predecessorNodes = this.GetShortestPathPredecessors(targetNode); foreach (var predecessor in predecessorNodes) { var node = new DistanceNode(predecessor.Name) { Tag = predecessor.Tag, }; if (!graph.TryAddNode(node)) { node = (DistanceNode)graph.GetNode(node.Name); } var distance = _distances[predecessor.Name]; node.Distance = distance; _graph.TryGetEdge(predecessor, targetNode, out var edge); if (graph.TryAddEdge(predecessor.Name, targetNode.Name, edge.Weight, false, out _)) { GetShortestGraph(sourceNode, predecessor, graph); } } }
protected DirectedGraph BuildShortestPathGraph(DirectedGraphNode sourceNode, DirectedGraphNode targetNode) { if (_distances[targetNode.Name] == double.PositiveInfinity) { throw new PathNotFoundException(sourceNode.Name, targetNode.Name); } var graph = new DirectedGraph(); //Set start Node var distanceNode = new DistanceNode(targetNode.Name) { Tag = targetNode.Tag }; var distance = _distances[targetNode.Name]; distanceNode.Distance = distance; graph.AddNode(distanceNode); GetShortestGraph(sourceNode, targetNode, graph); //set node distances foreach (var node in graph.Nodes) { node.Description = node.Name + Environment.NewLine + "Distance:" + _distances[node.Name].ToString(); } //set edge description foreach (var edge in graph.Edges) { edge.Description = edge.Weight.ToString(); } return(graph); }
/// <summary> /// Searches the shortest path to the Source node /// via the DeepFirst-Search Algorithm /// </summary> public static bool TryGetDistanceNode(this DirectedGraph graph, string nodeName, out DistanceNode distanceNode) { var result = graph.TryGetNode(nodeName, out var existingNode); if (result == true && existingNode is DistanceNode node) { distanceNode = node; return(true); } else { distanceNode = null; return(false); } }