public static void Main(string[] args) { #region create graph: https://en.wikipedia.org/wiki/Prim%27s_algorithm Graph graph = new Graph(); graph.AddEdges(0, 1, 2); graph.AddEdges(0, 3, 1); graph.AddEdges(1, 3, 2); graph.AddEdges(2, 3, 3); #endregion foreach (Edge e in PrimsAlgorithm(graph)) { Console.WriteLine(String.Format("Edge ({0}, {1})", e.vertexU, e.vertexV)); } Console.WriteLine("Press any key..."); Console.ReadKey(); }
public static List<Edge> PrimsAlgorithm(Graph graph) { List<Edge> minSpanningTree = new List<Edge>(); List<Edge> unselectedEdges = new List<Edge>(graph.Edges); List<int> unselectedVertices = new List<int>(graph.Vertices); List<int> selectedVertices = new List<int>(); // random selection of vertex selectedVertices.Add(new Random().Next(0, graph.Vertices.Count())); unselectedVertices.RemoveAt(selectedVertices[0]); while (unselectedVertices.Count > 0) { int indexMinEdge = -1; // search the minimum-weight edge for (int i = 0; i < unselectedEdges.Count; i++) { if ((selectedVertices.IndexOf(unselectedEdges[i].vertexU) != -1) && (unselectedVertices.IndexOf(unselectedEdges[i].vertexV) != -1) || (selectedVertices.IndexOf(unselectedEdges[i].vertexV) != -1) && (unselectedVertices.IndexOf(unselectedEdges[i].vertexU) != -1)) { indexMinEdge = indexMinEdge == -1 ? i : (unselectedEdges[i].weight < unselectedEdges[indexMinEdge].weight ? i : indexMinEdge); } } // add a new vertex (U or V) to the selected list and remove from list unselected if (selectedVertices.IndexOf(unselectedEdges[indexMinEdge].vertexU) != -1) { selectedVertices.Add(unselectedEdges[indexMinEdge].vertexV); unselectedVertices.Remove(unselectedEdges[indexMinEdge].vertexV); } else { selectedVertices.Add(unselectedEdges[indexMinEdge].vertexU); unselectedVertices.Remove(unselectedEdges[indexMinEdge].vertexU); } // add a new edge to the tree and delete from the list of unselected minSpanningTree.Add(unselectedEdges[indexMinEdge]); unselectedEdges.RemoveAt(indexMinEdge); } return minSpanningTree; }