Program.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. namespace DejkstraAlgorithm1
  5. {
  6. public class DejkstraAlgorithm
  7. {
  8. public static int V = 5;
  9. public static int MinDistance(int[] dist, bool[] sptSet)
  10. {
  11. int min = int.MaxValue, min_index = -1;
  12. for (int v = 0; v < V; v++)
  13. {
  14. if (!sptSet[v] && dist[v] <= min)
  15. {
  16. min = dist[v];
  17. min_index = v;
  18. }
  19. }
  20. return min_index;
  21. }
  22. public static void PrintSolution(int[] dist)
  23. {
  24. Console.WriteLine("Вершина \t Расстояние от вершины 1");
  25. for (int i = 0; i < V; i++)
  26. {
  27. Console.WriteLine(i + 1 + "\t \t \t" + dist[i]);
  28. }
  29. }
  30. public static int[] Dejkstra(int[,] graph, int src)
  31. {
  32. int[] dist = new int[V];
  33. bool[] sptSet = new bool[V];
  34. for (int i = 0; i < V; i++)
  35. {
  36. dist[i] = int.MaxValue;
  37. sptSet[i] = false;
  38. }
  39. dist[src] = 0;
  40. for (int i = 0; i < V - 1; i++)
  41. {
  42. int u = MinDistance(dist, sptSet);
  43. sptSet[u] = true;
  44. for (int v = 0; v < V; v++)
  45. {
  46. if (!sptSet[v] && graph[u, v] != 0 && dist[u] != int.MaxValue && (dist[u] + graph[u, v] < dist[v]))
  47. {
  48. dist[v] = dist[u] + graph[u, v];
  49. }
  50. }
  51. }
  52. PrintSolution(dist);
  53. return dist;
  54. }
  55. public static void Main()
  56. {
  57. int[,] graph = new int[,] {
  58. { 0, 4, 6, 7,0},
  59. { 4, 0, 0, 0,8},
  60. { 6, 0, 0, 1,2},
  61. { 7, 0, 1, 0,5},
  62. { 0, 8, 2, 5,0},
  63. };
  64. int[] c = Dejkstra(graph, 0);
  65. Trace.Listeners.Add(new TextWriterTraceListener(File.Open("trace.txt", FileMode.OpenOrCreate)));
  66. Trace.AutoFlush = true;
  67. Trace.WriteLine("Program complete");
  68. }
  69. }
  70. }