diff --git a/Computational_Algorithms/Greedy/prim's_algorithm.cpp b/Computational_Algorithms/Greedy/prim's_algorithm.cpp new file mode 100644 index 0000000..4f10a9f --- /dev/null +++ b/Computational_Algorithms/Greedy/prim's_algorithm.cpp @@ -0,0 +1,136 @@ +/*PRIM'S ALGORITHM FOR MINIMUM SPANNING TREE*/ + +/*if we have a graph whose nodes are connected to each other acyclic or cyclic and the paths have some + weight then we can find out the minimum weighted path which connects all node. +*/ + +/* OBSERVATIONS- + 1)if there are n nodes then there will be n-1 paths which connects all nodes. + 2)if we have 2 non connected graph then we can never find minimum spanning path using this algo. +*/ + +/*ALGORITHM + 1)create three arrays parent,weight,visited. + 2)initialise weight vector with max value and visited vector with false. + 3)we can start with any node(usually node 0) then select node whose path with this node is least + and update the parent for this node. + 4)as we select paths we will also update weights in weight array with minimum of weights + and value stored in weights array. + 5)once we have visited the node we update value in visited array as true. + 6)we then select minimum value in array weights and repeat step 4-6 till we get parent of + each node filled. +*/ + +#include +using namespace std; + +//finding node with minimum value of weight. +int node(vector& weight,vector& visited,int V) +{ + int minimum = INT_MAX; + int vertex; + for(int i=0;i> graph,int V) +{ + int parent[V];// creating parent array. + vector weight(V,INT_MAX);// setting weight of each node initially maximum/infinity. + vector visited(V,false);// setting initial visited array as false none visited. + + + parent[0] = -1; //as we are taking 0 is base node so it will have no parent + weight[0] = 0; //cost of going to node 0 from node 0 would be 0 + + + for(int i=0;i"<>V; + + vector> graph(V,vector(V)); + + int n; + cout<<"enter number of edges"<>n; + + for (int i = 0; i >p>>q; + if(p<0||p>V-1||q<0||q>V-1){ + cout<<"please keep input in range."<>val; + graph[p][q]=val; + graph[q][p]=val; + } + + /* adjacency matrix for inputs- + 6 10 + 0 1 4 + 0 2 6 + 1 2 6 + 1 3 3 + 1 4 4 + 2 4 8 + 4 5 7 + 2 3 1 + 3 4 2 + 3 5 3 + + would look like this- + + [[0, 4, 6, 0, 0, 0], + [4, 0, 6, 3, 4, 0], + [6, 6, 0, 1, 8, 0], + [0, 3, 1, 0, 2, 3], + [0, 4, 8, 2, 0, 7], + [0, 0, 0, 3, 7, 0]] + */ + + spanningTree(graph,V); + return 0; +} + +//TIME COMPLEXITY: O(V^2) but can be improved further like if we +// would have used adjacency list instead of matrix. \ No newline at end of file