using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MathMod { internal class DijkstrasAlgorithm { List> mainMatrix_; public DijkstrasAlgorithm(List> adjacencyMatrix) { mainMatrix_ = adjacencyMatrix; } public (Dictionary, Dictionary>) Solve(int from) { List> mainMatrix = Program.Init2DList(mainMatrix_); Dictionary results = Enumerable.Range(0, mainMatrix_.Count).Select(v => new { v, Program.inf }).ToDictionary(v => v.v, v => v.inf); Dictionary> paths = new Dictionary> (); Dictionary notVisited = Enumerable.Range(0, mainMatrix_.Count).Select(v => (v, true)).ToDictionary(v => v.v, v => v.Item2); results[from] = 0; paths[from] = new List(); while (notVisited.Any(x=> x.Value)) { int nearestVertex = notVisited.Where(v => v.Value == true).OrderBy(v => results[v.Key]).FirstOrDefault().Key; notVisited[nearestVertex] = false; for(int j=0; j < mainMatrix_[0].Count; ++j) {//если ребро существует и оно не родительское if (mainMatrix[nearestVertex][j] < Program.inf && notVisited[j]) {//если вершину надо продлить, продливаем, добавляем путь if (results[j] > results[nearestVertex] + mainMatrix[nearestVertex][j]) { results[j] = results[nearestVertex] + mainMatrix[nearestVertex][j]; paths[j] = Program.Init1DList(paths[nearestVertex]); paths[j].Add(j); } } } } return (results,paths); } } }