// The main function to check whether a given graph contains cycle or not public static int isCycle(GlobalMembers graph) { int V = graph.V; int E = graph.E; // Allocate memory for creating V sets subset[] subsets = new subset[V]; for (int i = 0; i < subsets.Length; ++i) { subsets[i] = new subset(); } for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } // Iterate through all edges of graph, find sets of both // vertices of every edge, if sets are same, then there is // cycle in graph. for (int e = 0; e < E; ++e) { int x = find(subsets, graph.edge[e].src); int y = find(subsets, graph.edge[e].dest); if (x == y) { return(1); } Union(subsets, x, y); } return(0); }
void KruskalMST() { Edge[] result = new Edge[V]; int e = 0; int i = 0; for (i = 0; i < V; ++i) { result[i] = new Edge(); } Array.Sort(edge); subset[] subsets = new subset[V]; for (i = 0; i < V; ++i) { subsets[i] = new subset(); } for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } i = 0; while (e < V - 1) { Edge next_edge = new Edge(); next_edge = edge[i++]; int x = find(subsets, next_edge.src); int y = find(subsets, next_edge.dest); if (x != y) { result[e++] = next_edge; Union(subsets, x, y); } } Console.WriteLine(""); garis(); Console.WriteLine("\nSetelah Dilakukan MST"); int minimumCost = 0; for (i = 0; i < e; ++i) { Console.WriteLine("Node = " + result[i].src + " Terhubung Ke Node = " + result[i].dest + " Dengan Ukuran Edge = " + result[i].weight); minimumCost += result[i].weight; } Console.WriteLine("Minimum Cost Spanning Tree = " + minimumCost); Console.ReadLine(); }
public void KruskalAlgorithm() { Edge[] result = new Edge[V]; int e = 0; int i = 0; for (i = 0; i < V; ++i) { result[i] = new Edge(); } Array.Sort(edge); subset[] subsets = new subset[V]; for (i = 0; i < V; ++i) { subsets[i] = new subset(); } for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } i = 0; while (e < V - 1) { Edge next_edge = new Edge(); next_edge = edge[i++]; int x = find(subsets, next_edge.src); int y = find(subsets, next_edge.dest); if (x != y) { result[e++] = next_edge; Union(subsets, x, y); } } Console.WriteLine("Минимальное остовное дерево:"); int minimumCost = 0; for (i = 0; i < e; ++i) { Console.WriteLine(result[i].src + " -- " + result[i].dest + " == " + result[i].weight); minimumCost += result[i].weight; } Console.WriteLine("Минимальный вес остовного дерева:" + minimumCost); }
// below function is belongs to kruskal algorithm public void Kruskal() { Edge[] result = new Edge[V]; int e = 0; int i = 0; for (i = 0; i < V; ++i) { result[i] = new Edge(); } System.Array.Sort(edge); // if you want to find ST you should comment in this line subset[] subsets = new subset[V]; for (i = 0; i < V; ++i) { subsets[i] = new subset(); } for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } i = 0; while (e < V - 1) { Edge next_edge = new Edge(); next_edge = edge[i++]; int x = find_Function(subsets, next_edge.src); int y = find_Function(subsets, next_edge.dest); if (x != y) { result[e++] = next_edge; union_Function(subsets, x, y); } } System.Console.WriteLine("Below edges are belong to Minimum Spanning Tree"); int totalweightofMST = 0; for (i = 0; i < e; ++i) { System.Console.WriteLine(result[i].src + " -- " + result[i].dest + " == " + result[i].weight); totalweightofMST += result[i].weight; } System.Console.WriteLine("The Total Weight of Minimum Spanning Tree is " + totalweightofMST); }
void KruskalMST() { Edge[] result = new Edge[V]; int e = 0; int i = 0; for (i = 0; i < V; ++i) { result[i] = new Edge(); } Array.Sort(edge); subset[] subsets = new subset[V]; for (i = 0; i < V; ++i) { subsets[i] = new subset(); } for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } i = 0; while (e < V - 1) { Edge next_edge = new Edge(); next_edge = edge[i++]; int x = find(subsets, next_edge.src); int y = find(subsets, next_edge.dest); if (x != y) { result[e++] = next_edge; Union(subsets, x, y); } } Console.WriteLine("src dst weight"); for (i = 0; i < e; ++i) { Console.WriteLine(result[i].src + " -- " + result[i].dest + " == " + result[i].weight); } Console.ReadLine(); }
public void KruskalMST() { Edge[] result = new Edge[V]; int j = 0; int i; for (i = 0; i < V; ++i) { result[i] = new Edge(); } Array.Sort(edge); subset[] subsets = new subset[V]; for (i = 0; i < V; ++i) { subsets[i] = new subset(); } for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } i = 0; while (j < V - 1) { Edge next_edge = new Edge(); next_edge = edge[i++]; int x = find(subsets, next_edge.src); int y = find(subsets, next_edge.dest); if (x != y) { result[j++] = next_edge; Union(subsets, x, y); } } for (i = 0; i < j; ++i) { Console.WriteLine(result[i].src + " to " + result[i].dest + " = " + result[i].weight); } }
List <edgeScript> kruskalMST(List <edgeScript> edges) { List <edgeScript> result = new List <edgeScript>(); int e = 0; int i = 0; List <edgeScript> sortedEdges = edges.OrderBy(se => se.getWeight()).ToList(); subset[] subsets = new subset[size * size]; for (i = 0; i < (size * size); i++) { subsets[i] = new subset(); } for (int v = 0; v < (size * size); v++) { subsets[v].parent = v; subsets[v].rank = 0; } i = 0; while (e < (size * size) - 1) { edgeScript next_edge = sortedEdges[i++]; int x = find(subsets, next_edge.getA()); int y = find(subsets, next_edge.getB()); if (x != y) { result.Add(next_edge); e++; union(subsets, x, y); } } return(result); }
// The main function to construct MST using Kruskal's algorithm void KruskalMST() { Edge [] result = new Edge[V]; // Tnis will store the resultant MST int e = 0; // An index variable, used for result[] int i = 0; // An index variable, used for sorted edges for (i = 0; i < V; ++i) { result[i] = new Edge(); } // Step 1: Sort all the edges in non-decreasing order of their // weight. If we are not allowed to change the given graph, we // can create a copy of array of edges Array.Sort(edge); // Allocate memory for creating V ssubsets subset [] subsets = new subset[V]; for (i = 0; i < V; ++i) { subsets[i] = new subset(); } // Create V subsets with single elements for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } i = 0; // Index used to pick next edge // Number of edges to be taken is equal to V-1 while (e < V - 1) { // Step 2: Pick the smallest edge. And increment // the index for next iteration Edge next_edge = new Edge(); next_edge = edge[i++]; int x = find(subsets, next_edge.src); int y = find(subsets, next_edge.dest); // If including this edge does't cause cycle, // include it in result and increment the index // of result for next edge if (x != y) { result[e++] = next_edge; Union(subsets, x, y); } // Else discard the next_edge } // print the contents of result[] to display // the built MST Console.WriteLine("Following are the edges in " + "the constructed MST"); for (i = 0; i < e; ++i) { Console.WriteLine(result[i].src + " -- " + result[i].dest + " == " + result[i].weight); } }
// The main function to construct MST // using Kruskal's algorithm public void KruskalMST() { // This will store the // resultant MST Edge[] result = new Edge[V]; int e = 0; // An index variable, used for result[] int i = 0; // An index variable, used for sorted edges for (i = 0; i < V; ++i) { result[i] = new Edge(); } // Step 1: Sort all the edges in non-decreasing // order of their weight. If we are not allowed // to change the given graph, we can create // a copy of array of edges Array.Sort(edge); // Allocate memory for creating V ssubsets subset[] subsets = new subset[V]; for (i = 0; i < V; ++i) { subsets[i] = new subset(); } // Create V subsets with single elements for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } i = 0; // Index used to pick next edge // Number of edges to be taken is equal to V-1 while (e < V - 1) { // Step 2: Pick the smallest edge. And increment // the index for next iteration Edge next_edge = new Edge(); next_edge = edge[i++]; int x = find(subsets, next_edge.source); int y = find(subsets, next_edge.destination); // If including this edge does't cause cycle, // include it in result and increment the index // of result for next edge if (x != y) { result[e++] = next_edge; Union(subsets, x, y); } // Else discard the next_edge } // print the contents of result[] to display // the built MST Console.WriteLine("Results of the Minimum Spanning Tree. \n"); int minimumCost = 0; for (i = 0; i < e; ++i) { string source = Dict[result[i].source], destination = Dict[result[i].destination]; int weight = result[i].weight; Console.WriteLine(source + " -- " + destination + " == " + weight); minimumCost += result[i].weight; } Console.WriteLine(" ------------------------------------ "); Console.WriteLine("Minimum Cost of the Spanning Tree: " + minimumCost); Console.WriteLine(" ------------------------------------ "); Console.ReadLine(); }
protected List <MyEdge> arr; //Здесь соберу все рёбра public void Button7_Click_1(object sender, EventArgs e) //КРАСКАЛ { //double[] edges = new double[(n * (n - 1) / 2)];// формула максимального числа рёбер(полного графа) arr = new List <MyEdge>(); for (int i = 0; i < n; i++)//Отрезаю нижний треугольник, т.к. граф неориентированный { for (int j = 0; j < i; j++) { mas[i, j] = double.PositiveInfinity; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (!Double.IsInfinity(mas[i, j]))//если не бесконечность, значит есть вершина { MyEdge me = new MyEdge(); me.from = i;//записал в ребро всю инфу me.to = j; me.vertice1 = dataGridView1.Rows[i].HeaderCell.Value.ToString(); me.vertice2 = dataGridView1.Columns[j].HeaderCell.Value.ToString(); me.weight = mas[i, j]; arr.Add(me); } } } if (arr.Count == 0) { return; } IEnumerable <MyEdge> query = arr.OrderBy(MyEdge => MyEdge.weight); //просто делает запрос, исходный массив не сортируется List <MyEdge> srtd = new List <MyEdge>(); //список отсортированных рёбер for (int i = 0; i < arr.Count; i++) {//добавил ссылки в новый массив. srtd вроде как получился индексным srtd.Add(query.ElementAt(i)); } int edgesNumber = srtd.Count; double k = Convert.ToDouble(edgesNumber); cntKrusc += k * Math.Log(k, 2); MyEdge[] result = new MyEdge[n - 1]; //в результирующем списке рёбер всегда будет n-1 int ee = 0; // индекс для масива result int ii = 0; // индекс для отсортированных рёбер subset[] subsets = new subset[n]; for (ii = 0; ii < n; ++ii)// выделяю память для n подмассивов { subsets[ii] = new subset(); subsets[ii].parent = ii; subsets[ii].rank = 0; } ii = 0; while (ee < n - 1) //пока не набрали n-1 рёбер { cntKrusc++; //подсчет одной попытки добавления ребра, результативной или нет, не важно MyEdge next_edge = new MyEdge(); next_edge = srtd[ii++]; //беру очередное ребро из списка отсортированных //сабсет изначально содержит все вершины в виде объектов subset //эти вершины представлены просто индексами каждого объекта сабсет. //А вот принадлежность к дереву изначально сама на себя(индекс сабсета и номер родителя одинаковы). //Т.е. вершина сама как бы является деревом, ссылаясь на себя. При добавлении новой вершины //она направляется на сабсет с индексом-номером этой, добавляемой вершины и ищет там своего предка, //гляда на родителя этого сабсета. Находит его и назначает себе. А при присоединении к вершине // с меньшим рангом всё равно ворзвращаешься на того же родителя. //Остановка происходит, когда добавлено n-1 рёбер. До этого может несколько рёбер пропустить, если //у обеих их вершин будет одинаковый предок. int x = find(subsets, next_edge.from); //ищем вершинки. Если они обе(их общие предки) уже есть int y = find(subsets, next_edge.to); //в сабсетах,то включение данного ребра бессмысленно if (x != y) //Если включение данного ребра не создаёт цикл(если общие предки вершин разные), то { //добавить его в result и увеличить индекс для выбора следующего ребра result[ee++] = next_edge; //добавить ребро в список Union(subsets, x, y); //добавить вершины в сабсеты(по сути назначить им общего родителя) cntKrusc++; //подсчет одной результативной попытки }//иначе игнорировать ребро } for (int i = 0; i < n; i++) {//Все вершины в бесконечность перед обновлением матрицы for (int j = 0; j < n; j++) { mas[i, j] = double.PositiveInfinity; dataGridView1.Rows[i].Cells[j].Value = mas[i, j]; } } for (int a = 0; a < result.Length; a++) {//засовываю в mas & datagridview пересчитанные Краскалом значения int i = result[a].from; int j = result[a].to; double w = result[a].weight; mas[i, j] = w; dataGridView1.Rows[i].Cells[j].Value = w; } textBox1.Text = Convert.ToString(Convert.ToInt32(cntKrusc)); cntKrusc = 0; }
// The main function to construct MST // using Kruskal's algorithm public Single[,] KruskalMST() { Edge[] result = new Edge[V]; // This will store the resultant MST int e = 0; // An index variable, used for result[] int i = 0; // An index variable, used for sorted edges for (i = 0; i < V; ++i) { result[i] = new Edge(); } // Step 1: Sort all the edges in non-decreasing // order of their weight. If we are not allowed // to change the given graph, we can create // a copy of array of edges Array.Sort(edge); // Allocate memory for creating V ssubsets subset[] subsets = new subset[V]; for (i = 0; i < V; ++i) { subsets[i] = new subset(); } // Create V subsets with single elements for (int v = 0; v < V; ++v) { subsets[v].parent = v; subsets[v].rank = 0; } i = 0; // Index used to pick next edge // Number of edges to be taken is equal to V-1 while (e < V - 1) { // Step 2: Pick the smallest edge. And increment // the index for next iteration Edge next_edge = new Edge(); next_edge = edge[i++]; int x = find(subsets, next_edge.src); int y = find(subsets, next_edge.dest); // If including this edge does't cause cycle, // include it in result and increment the index // of result for next edge if (x != y) { result[e++] = next_edge; Union(subsets, x, y); } // Else discard the next_edge } Single[,] finished = new Single[10, 10]; // print the contents of result[] to display // the built MST for (i = 0; i < e; ++i) { finished[result[i].src, result[i].dest] = result[i].weight; finished[result[i].dest, result[i].src] = result[i].weight; } return(finished); }