public void Kruskal() { int i; Queue Q = new Queue(this.m); DSStruct Z = new DSStruct(this.n); Result = new AdjacencyList(n); for (i = 0; i < n; i++) { Z.MakeSet(i); //tworz eosobny zbior dla kazdego wierzcholka } //umieszczam w kolejce kolejne krawedzie grafu /*for (i = 0; i < m; i++) * { * Q.Push(edges[i]); * }*/ for (i = 0; i < n; i++) { for (p = getAList(i); p != null; p = p.next) { e.v1 = i; e.v2 = p.v; e.weight = p.weight; Q.Push(e); } } for (i = 1; i < n; i++) { do { e = Q.front(); Q.Pop(); } while ((Z.FindSet(e.v1) == Z.FindSet(e.v2))); Result.addEdge(e); Z.UnionSets(e); } }
public void Prim() { int i, v; Queue Q = new Queue(this.m); Result = new AdjacencyList(n); bool[] visited = new bool[n]; for (i = 0; i < n; i++) { visited[i] = false; } v = 0; //wierzcholek startowy visited[v] = true; //odwiedzony wierzcholek startowy for (i = 1; i < n; i++) { for (p = getAListU(v); p != null; p = p.next) { if (!visited[p.v]) { e.v1 = v; e.v2 = p.v; e.weight = p.weight; Q.Push(e); } } do { e = Q.front(); Q.Pop(); } while (visited[e.v2]); Result.addEdge(e); visited[e.v2] = true; v = e.v2; } }
static void Main(string[] args) { string opt; string fileName; int v; int g; AdjacencyList AdjacencyList = new AdjacencyList(); AdjacencyMatrix AdjacencyMatrix = new AdjacencyMatrix(); do { Console.WriteLine("1. Wczytaj z pliku"); Console.WriteLine("2. Wygeneruj graf"); Console.WriteLine("3. Wyświetl"); Console.WriteLine("4. Algorytm Prima"); Console.WriteLine("5. Algorytm Kruskala"); Console.WriteLine("6. Algorytm Dijkstry"); Console.WriteLine("7. Algorytm Bellmana-Forda"); Console.WriteLine("0. Wyjdź"); opt = Convert.ToString(Console.ReadLine()); switch (opt) { case "1": Console.Write("Podaj nazwę pliku: "); fileName = Console.ReadLine(); AdjacencyList.LoadFromFile(fileName); AdjacencyMatrix.LoadFromFile(fileName); AdjacencyList.ShowList(); AdjacencyMatrix.ShowMatrix(); break; case "2": Console.WriteLine("Podaj liczbę wierzchołków: "); v = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Podaj gęstość: "); g = Convert.ToInt32(Console.ReadLine()); AdjacencyList.GenerateRandomGraph(v, g); AdjacencyList.ShowList(); AdjacencyMatrix.GenerateRandomGraph(v, g); AdjacencyMatrix.ShowMatrix(); break; case "3": AdjacencyList.ShowList(); AdjacencyMatrix.ShowMatrix(); break; case "4": AdjacencyList.Prim(); AdjacencyMatrix.Prim(); AdjacencyList.ShowMST(); AdjacencyMatrix.ShowMST(); break; case "5": AdjacencyList.Kruskal(); AdjacencyMatrix.Kruskal(); AdjacencyList.ShowMST(); AdjacencyMatrix.ShowMST(); break; case "6": AdjacencyList.Dijkstra(); AdjacencyMatrix.Dijkstra(); AdjacencyList.ShowShortestPaths(); AdjacencyMatrix.ShowShortestPaths(); break; case "7": AdjacencyList.BellmanFord(); AdjacencyMatrix.BellmanFord(); AdjacencyList.ShowShortestPaths(); AdjacencyMatrix.ShowShortestPaths(); break; } } while (opt != "0"); }