public IEnumerable <NodePath> FindMoves(Node start, int distance, IEnumerable <Node> occupiedNodes = null) { if (occupiedNodes == null) { occupiedNodes = new List <Node>(); } BoardGraph boardGraph = new BoardGraph(occupiedNodes.ToList()); NodeMapKey nodeMapKey = new NodeMapKey(start.Id, distance); List <NodePath> nodePaths = new List <NodePath>(); if (boardGraph.NodeMap.ContainsKey(nodeMapKey)) { nodePaths = boardGraph.NodeMap[new NodeMapKey(start.Id, distance)]; } return(nodePaths); }
// Well, it certainly ain't pretty, but it's past my bed time - ianb 20160831 private Dictionary <NodeMapKey, List <NodePath> > BuildMapForNode(List <Node> nodes, Node sourceNode) { List <Node> unvisitedNodes = new List <Node>(); Dictionary <Node, int> shortestDistanceToNode = new Dictionary <Node, int>(); Dictionary <Node, Node> previousNodeAlongShortestPath = new Dictionary <Node, Node>(); if (!nodes.Contains(sourceNode)) { shortestDistanceToNode.Add(sourceNode, 0); previousNodeAlongShortestPath.Add(sourceNode, null); unvisitedNodes.Add(sourceNode); } foreach (Node node in nodes) { shortestDistanceToNode.Add(node, int.MaxValue); previousNodeAlongShortestPath.Add(node, null); unvisitedNodes.Add(node); } while (unvisitedNodes.Any()) { unvisitedNodes.Sort((x, y) => shortestDistanceToNode[x] - shortestDistanceToNode[y]); Node currentNode = unvisitedNodes[0]; unvisitedNodes.Remove(currentNode); foreach (Node adjacentNode in currentNode.AdjacentNodes) { int currentPathDistance = shortestDistanceToNode[currentNode] + 1; if (currentPathDistance < shortestDistanceToNode[adjacentNode] && currentPathDistance > 0) { shortestDistanceToNode[adjacentNode] = currentPathDistance; previousNodeAlongShortestPath[adjacentNode] = currentNode; } } } Dictionary <NodeMapKey, List <NodePath> > shortestPathMap = new Dictionary <NodeMapKey, List <NodePath> >(); foreach (Node node in nodes) { int distance = 0; NodePath shortestPath = new NodePath { DestinationNode = node }; Node currentPathNode = node; while (previousNodeAlongShortestPath[currentPathNode] != null) { distance++; shortestPath.PathToDestination.Insert(0, currentPathNode); currentPathNode = previousNodeAlongShortestPath[currentPathNode]; } NodeMapKey currentTupleKey = new NodeMapKey(sourceNode.Id, distance); if (!shortestPathMap.Keys.Any(k => k.Equals(currentTupleKey))) { shortestPathMap.Add(currentTupleKey, new List <NodePath>()); } shortestPathMap[currentTupleKey].Add(shortestPath); } return(shortestPathMap); }