דצמ.30

dijkstra's algorithm

dijkstra's algorithm

יש למצוא מסלול הכי קצר עם התחשבות לזמן שלוקח להגיעה מנקודה לנקודה.

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. Graph g = new Graph();
  6. g.addVertex('A', new Dictionary<char, int>() { { 'B', 7 }, { 'C', 8 } });
  7. g.addVertex('B', new Dictionary<char, int>() { { 'A', 7 }, { 'F', 2 } });
  8. g.addVertex('C', new Dictionary<char, int>() { { 'A', 8 }, { 'F', 6 }, { 'G', 4 } });
  9. g.addVertex('D', new Dictionary<char, int>() { { 'F', 8 } });
  10. g.addVertex('E', new Dictionary<char, int>() { { 'H', 1 } });
  11. g.addVertex('F', new Dictionary<char, int>() { { 'B', 2 }, { 'C', 6 }, { 'D', 8 }, { 'G', 9 }, { 'H', 3 } });
  12. g.addVertex('G', new Dictionary<char, int>() { { 'C', 4 }, { 'F', 9 } });
  13. g.addVertex('H', new Dictionary<char, int>() { { 'E', 1 }, { 'F', 3 } });
  14.  
  15. g.shortestPath('A', 'H').ForEach(x => Console.WriteLine(x));
  16. Console.ReadKey();
  17. }
  18. }
  19.  
  20.  
  21. class Graph
  22. {
  23. Dictionary<char, Dictionary<char, int>> vertices = new Dictionary<char, Dictionary<char, int>>();
  24. public void addVertex(char name, Dictionary<char, int> edges)
  25. {
  26. vertices[name] = edges;
  27. }
  28. public List<char> shortestPath(char start, char finish)
  29. {
  30. var previous = new Dictionary<char, char>();
  31. var distances = new Dictionary<char, int>();
  32. var nodes = new List<char>();
  33. List<char> path = null;
  34.  
  35. foreach (var vertex in vertices)
  36. {
  37. if (vertex.Key == start)
  38. distances[vertex.Key] = 0;
  39. else
  40. distances[vertex.Key] = int.MaxValue;
  41.  
  42. nodes.Add(vertex.Key);
  43. }
  44. while (nodes.Count != 0)
  45. {
  46. nodes.Sort((x, y) => distances[x] - distances[y]);
  47.  
  48. var smallest = nodes[0];
  49. nodes.Remove(smallest);
  50.  
  51. if (smallest == finish)
  52. {
  53. path = new List<char>();
  54. while (previous.ContainsKey(smallest))
  55. {
  56. path.Add(smallest);
  57. smallest = previous[smallest];
  58. }
  59. break;
  60. }
  61.  
  62. if (distances[smallest] == int.MaxValue)
  63. break;
  64.  
  65. foreach (var neighbor in vertices[smallest])
  66. {
  67. var alt = distances[smallest] + neighbor.Value;
  68. if (alt < distances[neighbor.Key])
  69. {
  70. distances[neighbor.Key] = alt;
  71. previous[neighbor.Key] = smallest;
  72. }
  73. }
  74. }
  75. return path;
  76. }
  77. }


תגיות:
שתף את הסיפור הזה:

תגובות(0)

השאירו תגובה

קפטצ'ה לא מתאימה

תגובה