private void InitialiseGraph(Graph graph, string startingNode) { foreach (Node node in graph.Nodes.Values) { node.DistanceFromStart = double.PositiveInfinity; } graph.Nodes[startingNode].DistanceFromStart = 0; }
public IDictionary<string, double> CalculateDistances(Graph graph, string startingNode) { if (!graph.Nodes.Any(n => n.Key == startingNode)) { throw new ArgumentException("Starting node must be in graph."); } InitialiseGraph(graph, startingNode); ProcessGraph(graph, startingNode); return ExtractDistances(graph); }
private void ProcessGraph(Graph graph, string startingNode) { bool finished = false; var queue = graph.Nodes.Values.ToList(); while (!finished) { Node nextNode = queue.OrderBy(n => n.DistanceFromStart). FirstOrDefault(n => !double.IsPositiveInfinity(n.DistanceFromStart)); if (nextNode != null) { ProcessNode(nextNode, queue); queue.Remove(nextNode); } else { finished = true; } } }
public static void Main() { string[] firstLine = Console.ReadLine().Split(' '); int nodes = int.Parse(firstLine[0]); int edges = int.Parse(firstLine[1]); int numberOfHospitals = int.Parse(firstLine[2]); string[] hospitals = Console.ReadLine().Split(' '); Graph graph = new Graph(); for (int i = 1; i <= nodes; i++) { graph.AddNode(i.ToString()); } for (int i = 0; i < edges; i++) { string[] edge = Console.ReadLine().Split(' '); graph.AddConnection(edge[0], edge[1], int.Parse(edge[2]), true); } int minDistance = int.MaxValue; for (int i = 0; i < numberOfHospitals; i++) { var calculator = new DistanceCalculator(); var distances = calculator.CalculateDistances(graph, hospitals[i]); int currentDistance = 0; foreach (var distance in distances) { if (!hospitals.Contains(distance.Key)) { currentDistance += (int)distance.Value; } } if (currentDistance < minDistance) { minDistance = currentDistance; } } Console.WriteLine(minDistance); }
private IDictionary<string, double> ExtractDistances(Graph graph) { return graph.Nodes.ToDictionary(n => n.Key, n => n.Value.DistanceFromStart); }