DickstraMethod.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. namespace DickstraMethodd
  5. {
  6. internal class DickstraMethod
  7. {
  8. int start;
  9. string pathway;
  10. public DickstraMethod(string pathway)
  11. {
  12. this.pathway = pathway;
  13. }
  14. public void Dickstra()
  15. {
  16. double[,] graph = ReadFile(pathway);
  17. int n = graph.GetLength(0);
  18. double[] pointDistances = new double[n];
  19. bool[] visitedPoints = new bool[n];
  20. // Инициализация массивов
  21. InitializeArray(pointDistances, double.PositiveInfinity);
  22. InitializeArray(visitedPoints, false);
  23. pointDistances[start] = 0;
  24. for (int i = 0; i < n - 1; i++)
  25. {
  26. double minDistance = double.PositiveInfinity;
  27. int minIndex = -1;
  28. // Находим вершину с минимальным расстоянием
  29. for (int j = 0; j < n; j++)
  30. {
  31. if (!visitedPoints[j] && pointDistances[j] < minDistance)
  32. {
  33. minDistance = pointDistances[j];
  34. minIndex = j;
  35. }
  36. }
  37. visitedPoints[minIndex] = true;
  38. // Обновляем расстояния до смежных вершин
  39. for (int j = 0; j < n; j++)
  40. {
  41. if (!visitedPoints[j] && graph[minIndex, j] != 0 && pointDistances[minIndex] != double.PositiveInfinity &&
  42. pointDistances[minIndex] + graph[minIndex, j] < pointDistances[j])
  43. {
  44. pointDistances[j] = pointDistances[minIndex] + graph[minIndex, j];
  45. }
  46. }
  47. }
  48. Output(pointDistances);
  49. }
  50. public double[,] ReadFile(string pathway)
  51. {
  52. int n = File.ReadAllLines(pathway).Length;
  53. double[,] graph = new double[n, n];
  54. using (StreamReader reader = new StreamReader(pathway))
  55. {
  56. for (int i = 0; i < n; i++)
  57. {
  58. string text = reader.ReadLine();
  59. string[] mas = text.Split(new char[] { ',' });
  60. if (mas.Length == 1)
  61. {
  62. start = int.Parse(mas[0]);
  63. }
  64. else
  65. {
  66. for (int j = 0; j < mas.Length; j++)
  67. {
  68. graph[i, j] = double.Parse(mas[j]);
  69. }
  70. }
  71. }
  72. }
  73. return graph;
  74. }
  75. private void InitializeArray<T>(T[] array, T value)
  76. {
  77. for (int i = 0; i < array.Length; i++)
  78. {
  79. array[i] = value;
  80. }
  81. }
  82. private void Output(double[] shortestPathsways)
  83. {
  84. Console.WriteLine($"Кратчайшие пути от вершины {start + 1}:\n");
  85. for (int i = 0; i < shortestPathsways.Length; i++)
  86. {
  87. Console.WriteLine($"До вершины {i + 1}: {shortestPathsways[i]}");
  88. }
  89. }
  90. }
  91. }