I need help implementing the Dijkstra Algorithm and was hoping someone could help me. I have it so that it prints some routes, but does not fix the correct costs for the path.
Here is my node structure:
class Node
{
public enum Color {White, Gray, Black};
public string Name { get; set; }
public List<NeighborNode> Neighbors { get; set; }
public Color nodeColor = Color.White;
public int timeDiscover { get; set; }
public int timeFinish { get; set; }
public Node()
{
Neighbors = new List<NeighborNode>();
}
public Node(string n, int discover)
{
Neighbors = new List<NeighborNode>();
this.Name = n;
timeDiscover = discover;
}
public Node(string n, NeighborNode e, decimal m)
{
Neighbors = new List<NeighborNode>();
this.Name = n;
this.Neighbors.Add(e);
}
}
class NeighborNode
{
public Node Name { get; set; }
public decimal Miles { get; set; }
public NeighborNode() { }
public NeighborNode(Node n, decimal m)
{
Name = n;
Miles = m;
}
}
Here is my algorithm:
public void DijkstraAlgorithm(List<Node> graph)
{
List<DA> _algorithmList = new List<DA>();
Stack<Node> _allCities = new Stack<Node>();
Node _nodeToExamine = new Node();
decimal _cost = 0;
foreach (var city in graph)
{
_allCities.Push(city);
_algorithmList.Add(new DA(city));
}
_nodeToExamine = _allCities.Pop();
while (_allCities.Count != 0)
{
foreach (var neighbor in _nodeToExamine.Neighbors)
{
for (int i = 0; i < _algorithmList.Count; i++)
{
if (_algorithmList[i].Name.Name == neighbor.Name.Name)
{
for (int j = 0; j < _algorithmList.Count; j++)
{
if (_algorithmList[j].Name.Name == _nodeToExamine.Name)
{
if (_algorithmList[j].Cost != 100000000)
_cost = _algorithmList[j].Cost;
break;
}
}
_cost = _cost + neighbor.Miles;
if (_algorithmList[i].Cost > _cost)
{
_algorithmList[i].Parent = _nodeToExamine;
_algorithmList[i].Cost = _cost;
break;
}
}
}
}
_cost = 0;
_nodeToExamine = _allCities.Pop();
}
}
Here's what the graph looks like:

List of node graphs essentially
Node - Neighboring Nodes
So for example:
Node = Olympia, neighboring nodes = Lacy and Tacoma
source
share