Лошото е, че алгоритъмът на Дейкстра, който намерих:
- Код: Избери целия код
namespace Dijkstra
{
internal class Program
{
class Dijkstra
{
private int[,] mapMatrix;
private int[] distance;
private int[] visitedNodes;
public Dijkstra()
{
this.mapMatrix = new int[,]
{
{0, 2, 4, 6},
{2, 0, 2, 4},
{4, 2, 0, 2},
{6, 4, 2, 0}
};
this.distance = new int[this.mapMatrix.GetLength(0)];
this.visitedNodes = new int[this.mapMatrix.GetLength(0)];
}
public void DijikstraAlgorithm()
{
for (int i = 0; i < this.distance.Length; i++)
{
if (this.mapMatrix[0, i] == 0)
{
this.distance[i] = int.MaxValue;
}
else
{
this.distance[i] = this.mapMatrix[0, i];
}
this.visitedNodes[i] = i;
}
this.visitedNodes[0] = -1;
for (int j = 0; j < this.distance.Length / 2; j++)
{
int currentShortestWay = int.MaxValue;
int nextNodeOnShortestWay = 0;
for (int i = 0; i < this.distance.Length; i++)
{
if ((this.distance[i] < currentShortestWay) && (this.visitedNodes[i] != -1))
{
currentShortestWay = this.distance[i];
nextNodeOnShortestWay = i;
}
}
for (int i = 0; i < this.distance.Length; i++)
{
if (this.visitedNodes[i] != -1)
{
if (this.mapMatrix[nextNodeOnShortestWay, i] != 0)
{
if (this.distance[i] > this.distance[nextNodeOnShortestWay] +
this.mapMatrix[nextNodeOnShortestWay, i])
{
int newDistance = this.distance[nextNodeOnShortestWay] +
this.mapMatrix[nextNodeOnShortestWay, i];
this.distance[i] = newDistance;
}
}
}
}
this.visitedNodes[nextNodeOnShortestWay] = -1;
}
}
public void PrintShortestWays()
{
for (int i = 0; i < this.distance.Length; i++)
{
if (this.distance[i] == int.MaxValue)
{
Console.WriteLine("The shortest way to node: {0}, is – \"start point\"", i + 1);
}
else
{
Console.WriteLine("The shortest way to node: {0}, is – {1}",
i + 1, this.distance[i]);
}
}
}
}
static void Main(string[] args)
{
Dijkstra test = new Dijkstra();
test.DijikstraAlgorithm();
test.PrintShortestWays();
}
}
}
намира само дължината на ной-кратките пътища от даден град до всички останали, но не и самите пътища по градове, през които се минава. А ако ще се прави меморизация на най-кратките пътища, по-лесен ми се струва записът на Python в сравнение със C#.