-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumSpanningTree.cs
More file actions
51 lines (45 loc) · 1.3 KB
/
MinimumSpanningTree.cs
File metadata and controls
51 lines (45 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Collections.Generic;
using DA.DataStructures.Tree;
using DA.Graphs;
namespace DA.Algorithms.TreeAlgorithms
{
internal static class MinimumSpanningTree
{
public static void Prims (Graph graph)
{
int[] previous = new int[graph.Count];
int[] destination = new int[graph.Count];
int source = -1;
for (int i = 0; i < graph.Count; i++)
{
previous[i] = i;
destination[i] = int.MaxValue;
}
destination[source] = 0;
previous[source] = -1;
PriorityQueue<Graph.Node> queue = new PriorityQueue<Graph.Node> ();
Graph.Node node = new Graph.Node (source, source, 0);
queue.Enqueue (node);
while (queue.Count != 0)
{
node = queue.Peek ();
queue.Dequeue ();
Graph.List list = graph.GetList (node.destination);
Graph.Node currentNode = list.head;
while (currentNode != null)
{
int currentCost = currentNode.cost;
if (currentCost < destination[currentNode.destination])
{
destination[currentNode.destination] = currentCost;
previous[currentNode.destination] = currentNode.source;
node = new Graph.Node (currentNode.source, currentNode.destination, currentCost);
queue.Enqueue (node);
}
currentNode = currentNode.next;
}
}
}
}
}