From 7d03ffdfea0ab633296cb5877087e80ab4cd0cc2 Mon Sep 17 00:00:00 2001 From: Apurwa lohia <74809495+apurwa-lohia@users.noreply.github.com> Date: Fri, 21 Oct 2022 04:29:14 +0530 Subject: [PATCH 1/2] Create prim's-algorithm.cpp --- Coding/prim's-algorithm.cpp | 74 +++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Coding/prim's-algorithm.cpp diff --git a/Coding/prim's-algorithm.cpp b/Coding/prim's-algorithm.cpp new file mode 100644 index 00000000..1cd4a74d --- /dev/null +++ b/Coding/prim's-algorithm.cpp @@ -0,0 +1,74 @@ +#include +using namespace std; + +#define V 5 + +int minKey(int key[], bool mstSet[]) +{ + + int min = INT_MAX, min_index; + + for (int v = 0; v < V; v++) + if (mstSet[v] == false && key[v] < min) + min = key[v], min_index = v; + + return min_index; +} + +void printMST(int parent[], int graph[V][V]) +{ + cout<<"Edge \tWeight\n"; + for (int i = 1; i < V; i++) + cout< Date: Fri, 21 Oct 2022 04:30:33 +0530 Subject: [PATCH 2/2] Create kruskals_msp.cpp --- Coding/kruskals_msp.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Coding/kruskals_msp.cpp diff --git a/Coding/kruskals_msp.cpp b/Coding/kruskals_msp.cpp new file mode 100644 index 00000000..f3a42906 --- /dev/null +++ b/Coding/kruskals_msp.cpp @@ -0,0 +1,36 @@ +#include +using namespace std; + +#define V 6 +#define INFINITY 99999 + +int graph[V][V] = {{0, 4, 1, 4, INFINITY, INFINITY}, + {4, 0, 3, 8, 3, INFINITY}, + {1, 3, 0, INFINITY, 1, INFINITY}, + {4, 8, INFINITY, 0, 5, 7}, + {INFINITY, 3, 1, 5, 0, INFINITY}, + {INFINITY, INFINITY, INFINITY, 7, INFINITY, 0}}; + +void findMinimumEdge() { + for (int i = 0; i < V; i++) { + int min = INFINITY; + int minIndex = 0; + for (int j = 0; j < V; j++) { + if (graph[i][j] != 0 && graph[i][j] < min) { + min = graph[i][j]; + minIndex = j; + } + } + cout << i << " - " << minIndex << "\t" << graph[i][minIndex] << "\n"; + } +} + +int main() { + findMinimumEdge(); + return 0; +} + + +//1. Sort all the edges in non-decreasing order of their weight. +//2. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it. +//3. Repeat step#2 until there are (V-1) edges in the spanning tree.