summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorToby Vincent <tobyv13@gmail.com>2021-03-28 01:53:40 +0000
committerToby Vincent <tobyv13@gmail.com>2021-03-28 01:53:40 +0000
commitec967b2bcfd6af1a76408e1f733792c1a23c804a (patch)
tree9a0881bbccbd7c8b8780eb4f9b0048509942003b
parent45399d345002aac87a46a5156b06342724697df7 (diff)
added more documentation and cleaned up code
-rw-r--r--GraphExtensions.cs24
1 files changed, 17 insertions, 7 deletions
diff --git a/GraphExtensions.cs b/GraphExtensions.cs
index e36089f..4d5e468 100644
--- a/GraphExtensions.cs
+++ b/GraphExtensions.cs
@@ -1,5 +1,4 @@
using System;
-using System.Linq;
using Graph;
using PriorityQueue;
@@ -12,46 +11,57 @@ namespace PrimDijkstra.Extensions
public static class GraphExtensions
{
- // Lambda function for Prim's Algorithm
+ // lambda function for Prim's Algorithm
public static Func<double, double, double> Prim = (_, weight) =>
weight;
- // Lambda function for Dijkstra's Algorithm
+ // lambda function for Dijkstra's Algorithm
public static Func<double, double, double> Dijkstra = (u, weight) =>
weight + u;
- // Shared code for Prim and Dijkstra
+ // shared code for Prim and Dijkstra
public static Graph PrimDijkstra(this Graph graph, int init, Func<double, double, double> weightCalc)
{
// initialize Prim/Dijkstra
Graph primDijkstra = new Graph();
Queue queue = new Queue(graph.Vertices.Count, isMin: true);
- // Insert all verticies into queue
+ // insert all verticies into queue
graph.Vertices.ForEach(vertex =>
{
+ // set each key to infinity
vertex.Key = double.MaxValue;
queue.Insert(vertex);
});
- // Initialize init index
+ // initialize init index
queue.ChangeKey(init, 0);
- // Parse queue into MST or SPT
+ // parse queue into MST or SPT
while (!queue.IsEmpty())
{
+ // extracted vertex with smallest key from queue
Vertex vertex = queue.Extract();
+
+ // iterate through that vertex edges
vertex.Edges.ForEach(edge =>
{
+ // set weight equal to result of lambda function
double weight = weightCalc(vertex.Key, edge.Weight);
+
+ // check if neighbor is still in queue, and has a key larger than weight
if (queue[edge.V] != null && weight < queue[edge.V].Key)
{
+ // if so, set it's parent to this vertex, and it's key to weight
queue[edge.V].Parent = vertex.Id;
queue.ChangeKey(edge.V, weight);
}
});
+
+ // add extracted vertex to the new graph
primDijkstra.Vertices.Add(vertex);
}
+
return primDijkstra;
}
}