/// <summary> /// Method for running path calculation for each pair in input file /// </summary> /// <param name="map">Map of graph</param> /// <param name="question">List of pairs of nodes to find distance between</param> private static void FindAllPaths(ref int[,] map, List <string[]> question) { GraphPath path; foreach (string[] startEnd in question) { path = new GraphPath(); FindPath(startEnd); } }
/// <summary> /// Main part of Dijkstra's algorythm /// </summary> /// <param name="startEnd">Star and end nodes</param> private static void FindPath(string[] startEnd) { char startNode = startEnd[0][0]; char endNode = startEnd[1][0]; int row; int size = map.GetLength(0); PriorityQueue queue = new PriorityQueue(); queue.Enqueue(new Tuple <char, int, char>(startNode, 0, startNode)); Dictionary <char, int[]> visited = new Dictionary <char, int[]>(); while (queue.Count > 0) { Tuple <char, int, char> currentNode = queue.Dequeue(); char previousNode = currentNode.Item3; row = currentNode.Item1 - 65; int currentDistance = currentNode.Item2; if (!visited.ContainsKey(currentNode.Item1)) { visited.Add(currentNode.Item1, new int[] { currentDistance, previousNode }); } else if (visited.ContainsKey(currentNode.Item1) && visited[currentNode.Item1][0] > currentNode.Item2) { visited[currentNode.Item1][0] = currentNode.Item2; visited[currentNode.Item1][1] = previousNode; } for (int i = 0; i < size; i++) { if (map[row, i] != 0 && !visited.ContainsKey((char)(i + 65))) { queue.Enqueue(new Tuple <char, int, char>((char)(i + 65), map[row, i] + currentDistance, currentNode.Item1)); } } } if (visited.ContainsKey(endNode)) { GraphPath result = RebuildPath(visited, startEnd); Console.WriteLine(result); } else { Console.WriteLine($"No path found between {startNode} and {endNode}!"); } }
/// <summary> /// Method for finding out final path based on list of distances from begining /// </summary> /// <param name="visited">List of nodes accessible from start node and distances from it with previous nodes for each other</param> /// <param name="startEnd">Path start and end</param> /// <returns></returns> private static GraphPath RebuildPath(Dictionary <char, int[]> visited, string[] startEnd) { char startNode = startEnd[0][0]; char endNode = startEnd[1][0]; char currentNode = endNode; GraphPath result = new GraphPath(); result.Length = visited[endNode][0]; result.Nodes.Add(currentNode.ToString()); while (currentNode != startNode) { currentNode = (char)visited[currentNode][1]; result.Nodes.Add(currentNode.ToString()); } return(result); }