I am new to advanced algorithms, so please bear with me. I am currently trying to get Dijkstra's algorithm to work, and have spend 2 days trying to figure this out. I also read the pseudo-code on Wikipedia and got this far. I want to get the shortest distance between two vertices. In the below sample, I keep getting the wrong distance. Please help?
Sample graph setup is as follow:
Graph graph = new Graph();
graph.Vertices.Add(new Vertex("A"));
graph.Vertices.Add(new Vertex("B"));
graph.Vertices.Add(new Vertex("C"));
graph.Vertices.Add(new Vertex("D"));
graph.Vertices.Add(new Vertex("E"));
graph.Edges.Add(new Edge
{
From = graph.Vertices.FindVertexByName("A"),
To = graph.Vertices.FindVertexByName("B"),
Weight = 5
});
graph.Edges.Add(new Edge
{
From = graph.Vertices.FindVertexByName("B"),
To = graph.Vertices.FindVertexByName("C"),
Weight = 4
});
graph.Edges.Add(new Edge
{
From = graph.Vertices.FindVertexByName("C"),
To = graph.Vertices.FindVertexByName("D"),
Weight = 8
});
graph.Edges.Add(new Edge
{
From = graph.Vertices.FindVertexByName("D"),
To = graph.Vertices.FindVertexByName("C"),
Weight = 8
});
//graph is passed as param with source and dest vertices
public int Run(Graph graph, Vertex source, Vertex destvertex)
{
Vertex current = source;
List<Vertex> queue = new List<Vertex>();
foreach (var vertex in graph.Vertices)
{
vertex.Weight = int.MaxValue;
vertex.PreviousVertex = null;
vertex.State = VertexStates.UnVisited;
queue.Add(vertex);
}
current = graph.Vertices.FindVertexByName(current.Name);
current.Weight = 0;
queue.Add(current);
while (queue.Count > 0)
{
Vertex minDistance = queue.OrderBy(o => o.Weight).FirstOrDefault();
queue.Remove(minDistance);
if (current.Weight == int.MaxValue)
{
break;
}
minDistance.Neighbors = graph.GetVerTextNeigbours(current);
foreach (Vertex neighbour in minDistance.Neighbors)
{
Edge edge = graph.Edges.FindEdgeByStartingAndEndVertex(minDistance, neighbour);
int dist = minDistance.Weight + (edge.Weight);
if (dist < neighbour.Weight)
{
//from this point onwards i get stuck
neighbour.Weight = dist;
neighbour.PreviousVertex = minDistance;
queue.Remove(neighbour);
queueVisited.Enqueue(neighbor);
}
}
minDistance.State = VertexStates.Visited;
}
//here i want to record all node that was visited
while (queueVisited.Count > 0)
{
Vertex temp = queueVisited.Dequeue();
count += temp.Neighbors.Sum(x => x.Weight);
}
return count;
}