123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- namespace DickstraMethodd
- {
- internal class DickstraMethod
- {
- int start;
- string pathway;
- public DickstraMethod(string pathway)
- {
- this.pathway = pathway;
- }
- public void Dickstra()
- {
- double[,] graph = ReadFile(pathway);
- int n = graph.GetLength(0);
- double[] pointDistances = new double[n];
- bool[] visitedPoints = new bool[n];
- // Инициализация массивов
- InitializeArray(pointDistances, double.PositiveInfinity);
- InitializeArray(visitedPoints, false);
- pointDistances[start] = 0;
- for (int i = 0; i < n - 1; i++)
- {
- double minDistance = double.PositiveInfinity;
- int minIndex = -1;
- // Находим вершину с минимальным расстоянием
- for (int j = 0; j < n; j++)
- {
- if (!visitedPoints[j] && pointDistances[j] < minDistance)
- {
- minDistance = pointDistances[j];
- minIndex = j;
- }
- }
- visitedPoints[minIndex] = true;
- // Обновляем расстояния до смежных вершин
- for (int j = 0; j < n; j++)
- {
- if (!visitedPoints[j] && graph[minIndex, j] != 0 && pointDistances[minIndex] != double.PositiveInfinity &&
- pointDistances[minIndex] + graph[minIndex, j] < pointDistances[j])
- {
- pointDistances[j] = pointDistances[minIndex] + graph[minIndex, j];
- }
- }
- }
- Output(pointDistances);
- }
- public double[,] ReadFile(string pathway)
- {
- int n = File.ReadAllLines(pathway).Length;
- double[,] graph = new double[n, n];
- using (StreamReader reader = new StreamReader(pathway))
- {
- for (int i = 0; i < n; i++)
- {
- string text = reader.ReadLine();
- string[] mas = text.Split(new char[] { ',' });
- if (mas.Length == 1)
- {
- start = int.Parse(mas[0]);
- }
- else
- {
- for (int j = 0; j < mas.Length; j++)
- {
- graph[i, j] = double.Parse(mas[j]);
- }
- }
- }
- }
- return graph;
- }
- private void InitializeArray<T>(T[] array, T value)
- {
- for (int i = 0; i < array.Length; i++)
- {
- array[i] = value;
- }
- }
- private void Output(double[] shortestPathsways)
- {
- Console.WriteLine($"Кратчайшие пути от вершины {start + 1}:\n");
- for (int i = 0; i < shortestPathsways.Length; i++)
- {
- Console.WriteLine($"До вершины {i + 1}: {shortestPathsways[i]}");
- }
- }
- }
- }
|