DijkstrasAlgorithm.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace MathMod
  7. {
  8. internal class DijkstrasAlgorithm
  9. {
  10. List<List<double>> mainMatrix_;
  11. public DijkstrasAlgorithm(List<List<double>> adjacencyMatrix)
  12. {
  13. mainMatrix_ = adjacencyMatrix;
  14. }
  15. public (Dictionary<int, double>, Dictionary<int, List<int>>) Solve(int from)
  16. {
  17. List<List<double>> mainMatrix = Program.Init2DList(mainMatrix_);
  18. Dictionary<int, double> results = Enumerable.Range(0, mainMatrix_.Count).Select(v => new { v, Program.inf }).ToDictionary(v => v.v, v => v.inf);
  19. Dictionary<int, List<int>> paths = new Dictionary<int, List<int>> ();
  20. Dictionary<int, bool> notVisited = Enumerable.Range(0, mainMatrix_.Count).Select(v => (v, true)).ToDictionary(v => v.v, v => v.Item2);
  21. results[from] = 0;
  22. paths[from] = new List<int>();
  23. while (notVisited.Any(x=> x.Value))
  24. {
  25. int nearestVertex = notVisited.Where(v => v.Value == true).OrderBy(v => results[v.Key]).FirstOrDefault().Key;
  26. notVisited[nearestVertex] = false;
  27. for(int j=0; j < mainMatrix_[0].Count; ++j)
  28. {//если ребро существует и оно не родительское
  29. if (mainMatrix[nearestVertex][j] < Program.inf && notVisited[j])
  30. {//если вершину надо продлить, продливаем, добавляем путь
  31. if (results[j] > results[nearestVertex] + mainMatrix[nearestVertex][j])
  32. {
  33. results[j] = results[nearestVertex] + mainMatrix[nearestVertex][j];
  34. paths[j] = Program.Init1DList(paths[nearestVertex]);
  35. paths[j].Add(j);
  36. }
  37. }
  38. }
  39. }
  40. return (results,paths);
  41. }
  42. }
  43. }