static void Main(string[] args) { int[,] edges = new int[, ] { { 0, 1 }, { 1, 2 }, { 2, 3 }, { 3, 4 }, { 4, 5 }, { 5, 6 }, { 6, 3 }, { 6, 0 }, { 6, 1 }, { 1, 3 } }; int[] weights = new int[10] { 1, 2, 1, 3, 2, 2, 1, 3, 3, 4 }; IGraph graph = new GraphAdjacencyList(7); for (int i = 0; i < 10; i++) { graph.AddEdge(graph.GetVertex(edges[i, 0]), graph.GetVertex(edges[i, 1]), weights[i]); } // IGraph sceleton = GraphWorker.Prim(graph); // sceleton.Edges().ForEach(edge => // { // Console.Out.WriteLine(edge.ToString()); // }); GraphProps graphProps = GraphWorker.WaveAlgorithm(graph, graph.GetVertex(0)); Console.Out.WriteLine(graphProps); graph.Vertices().ForEach(vertex => { Console.Out.WriteLine(vertex.ToString()); }); }
public static IGraph Kraskal(IGraph graph) { int size = graph.Size; IGraph sceleton = new GraphAdjacencyList(size); List <Edge> edges = graph.Edges(); edges.Sort((e1, e2) => (int)(e1.Weight - e2.Weight)); int[] components = new int[size]; for (int i = 0; i < size; i++) { components[i] = i; } int k = 0; while (k < size - 1) { Edge edge = edges.First(); if (components[edge.FirstVertex.Index] != components[edge.SecondVertex.Index]) { sceleton.AddEdge(edge); int first = edge.FirstVertex.Index; int second = edge.SecondVertex.Index; for (int i = 0; i < size; i++) { if (components[i] == second) { components[i] = first; } } k++; } edges.Remove(edge); } return(sceleton); }
public static IGraph Prim(IGraph graph) { IGraph sceleton = new GraphAdjacencyList(graph.Size); Vertex start = graph.GetVertex(0); List <Vertex> passed = new List <Vertex>(); passed.Add(start); start.Colour = 1; while (passed.Count != graph.Size) { double minWeight = Double.PositiveInfinity; Edge minEdge = null; Edge temp; passed.ForEach(vertex => { graph.Surrounding(vertex).ForEach(surround => { if (surround.Colour == 0) { temp = graph.GetEdge(vertex, surround); if (temp.Weight < minWeight) { minWeight = temp.Weight; minEdge = temp; } } }); }); Vertex next = graph.GetVertex(minEdge.SecondVertex.Index); sceleton.AddEdge(minEdge); next.Colour = 1; passed.Add(next); } return(sceleton); }