Question

In this problem, you are expected to implement Prims Algorithm on an undirected simple graph. Write a method that is part ofNotes: • Assume the given graph will be non-empty • Your algorithm should start at the edge with the lowest weight. Edges sho1 #define MAXNUMVERTICES 100 2 #include <iostream> 3 #include <set> 4 #include <vector> 5 #include <map> 6 #include <climits>

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Ans:

Program (Language : CPP)

#define MAXNUMVERTICES 108
#include <iostream>
#include <set>
#include <vector>
#include <map>
#include <climits>
using namespace std;

class Graph{
   private:
   int theGraph[MAXNUMVERTICES][MAXNUMVERTICES]={0};      //Adjacency matrix storing the graph
   set<int> vertices;                                     //Set storing all the vertices
   public:
   void insertEdge(int from, int to, int weight);         //Method to insert edge
   void insertVertex(int x);                   //Method to insert vertex in set
   void primMST();                           //Method for finding minimum spanning tree
   bool checkValidity(vector<bool> &inMST,int from, int to);    //Method checking edge can be added to MST or not at each step
};

void Graph::insertEdge(int to, int from, int weight){      //Method Defination
   this->theGraph[to][from] = weight;
   this->theGraph[from][to] = weight;
   }
  
void Graph::insertVertex(int x){                          //Method Defination
   this->vertices.insert(x);
}

bool Graph::checkValidity(vector<bool> &inMST,int from, int to){    
   if(from==to)                       // if both vertices are same
          return 0;
    if(inMST[from]==0 && inMST[to]==0) //if both vertices are not in MST
           return 0;
    if (inMST[from]==1 && inMST[to]==1) //if both vertices are already in MST
           return 0;
   return 1;
}

void Graph::primMST(){
  
    int V = (int) this->vertices.size();
    vector<bool> inMST(V+1, 0);
   // include first vertex in MST
    inMST[1] = true;
   // keep adding edges while number of included edges does not become V-1
    int edge_count = 0, mincost = 0;    // mincost stores the MST minimum cost
    while(edge_count<(V-1)){
                                       // Find minimum weight valid edge
        int min = INT_MAX, a = -1, b = -1;
        for(int i = 1; i <=V ; i++){
            for(int j = 1; j <=V ; j++){              
                if(this->theGraph[i][j] < min && this->theGraph[i][j]!=0){
                    if(this->checkValidity(inMST,i, j)){
                        min = this->theGraph[i][j];
                        a = i;
                        b = j;
                    }
                }
            }
        }
      
        if(a!=-1 && b!=-1){
           cout<<a<<" "<<b<<endl;         //print out the added edge
           edge_count++;
            mincost = mincost + min;
            inMST[b] = 1;
            inMST[a] = 1;
        }
    }
}

int main(){
   Graph *myGraph = new Graph();
   int numEdges, inVert, outVert, wt;
   std::cin>>numEdges;
   for(int i=0; i<numEdges; i++){                 //Reading graph and storing it in matrix
       std::cin>>inVert;
       std::cin>>outVert;
       std::cin>>wt;
       myGraph->insertEdge(inVert, outVert, wt);
       myGraph->insertVertex(inVert);
       myGraph->insertVertex(outVert);
   }
   myGraph->primMST();
}

Code Screenshots

1 #define MAXNUMVERTICES 108 2 #include <iostream> 3 #include <set> 4 #include <vector> 5 #include <map> 6 #include <climits>

28 29 bool Graph::checkvalidity (vector<bool> &inMST, int from, int to){ 30 if(from==to) // if both vertices are same 31 retu

} سها 60 61 62 if(a!=-1 && b!=-1){ 63 cout<<a<< <<b<<endl; //print out the added edge 64 edge_count++; 65 mincost = mincost

Input

18 212 1 3133 4147 5236 64 32 736 10 8358 9564 10

Output

12 13 34 35 56

Add a comment
Know the answer?
Add Answer to:
In this problem, you are expected to implement Prim's Algorithm on an undirected simple graph. Write...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Use Prim's algorithm (Algorithm 4.1) to find a minimum spanning tree for he following graph. Show...

    Please solve the problem in a clear word document not hand writing Use Prim's algorithm (Algorithm 4.1) to find a minimum spanning tree for he following graph. Show the actions step by step. 32 17 45 18 10 28 4 25 07 59 V10 4 12 4.1 MINIMUM SPANNING TREES 161 void prim (int n const number Wll set of.edges& F) index i, vnear; number min edge e; index nearest [2.. n]; number distance [2.. n]; for (i= 2; i...

  • Consider the weighted graph below: Demonstrate Prim's algorithm starting from vertex A. Write the edges in...

    Consider the weighted graph below: Demonstrate Prim's algorithm starting from vertex A. Write the edges in the order they were added to the minimum spanning tree. Demonstrate Dijkstra's algorithm on the graph, using vertex A as the source. Write the vertices in the order which they are marked and compute all distances at each step.

  • QUESTION 21 Suppose Prim's algorithm is being used find a minimal weight spanning tree for the...

    QUESTION 21 Suppose Prim's algorithm is being used find a minimal weight spanning tree for the graph below. 4 B3 If C is the initial vertex, Give the vertex set and the edge set of the subtree after 3 iterations (at this point, your subtree should have 3 edges.)

  • Given the following weighted graph G. use Prim's algorithm to determine the Minimum-Cost Spanning Tree (MCST)...

    Given the following weighted graph G. use Prim's algorithm to determine the Minimum-Cost Spanning Tree (MCST) with node 1 as the "root". List the vertices in the order in which the algorithm adds them to the solution, along with the edge and its weight used to make the selection, one per line. Each line should look like this: add vertex y: edge = (x,y), weight = 5 When the algorithm ends there are, generally, edges left in the heap. List...

  • Write a c or c++ program to write a prims algorithm and for problem 2(b) use kruskal algorithm.

    write a c or c++ program to write a prims algorithm and for problem 2(b) use kruskal algorithm. Problem 2 (A) (Prim's Algorithm): Apply Prim's algorithm to the following graph. Include in the priority queue only the fringe vertices (the vertices not in the current tree which are adjacent to at least one tree vertex) Problem 2 (B) (Kruskal Algorithm): Apply Kruskaľ's algorithm to find a minimum spanning tree of the following graphs. 4 3 2 2 4 3 6...

  • /* Graph read from file, and represnted as adjacency list. To implement DFS and BFS on...

    /* Graph read from file, and represnted as adjacency list. To implement DFS and BFS on the graph */ #include <iostream> #include <sstream> #include <fstream> #include <vector> #include <utility> #include <unordered_map> #include <set> #include <queue> using namespace std; // Each vertex has an integer id. typedef vector<vector<pair<int,int>>> adjlist; // Pair: (head vertex, edge weight) adjlist makeGraph(ifstream& ifs); void printGraph(const adjlist& alist); vector<int> BFS(const adjlist& alist, int source); // Return vertices in BFS order vector<int> DFS(const adjlist& alist, int source); //...

  • PYTHON ONLY Implement the Dijkstra’s Shortest path algorithm in Python. A graph with 10 nodes (Node...

    PYTHON ONLY Implement the Dijkstra’s Shortest path algorithm in Python. A graph with 10 nodes (Node 0 to node 9) must be implemented. You are supposed to denote the distance of the edges via an adjacency matrix (You can assume the edge weights are either 0 or a positive value). The adjacency matrix is supposed to be a 2-D array and it is to be inputted to the graph. Remember that the adjacency list denotes the edge values for the...

  • Hi there. I tried to submit this before, but the copy/paste didn't copy my vectors correctly....

    Hi there. I tried to submit this before, but the copy/paste didn't copy my vectors correctly. Hello there. I am trying to implement the djikstras shortest path algorithm into my code in C++ with a vector of vectors. However, when I test I get an error "Exception thrown at 0x75FFC762 in graphMain.exe: Microsoft C++ exception: std::out_of_range at memory location 0x009CF26C" for line 115 in graph.cpp. Could you help me debug? I am so close! ----------------------------FILE NAME: pch.h--------------------------------------- // pch.cpp: source...

  • 3. In this problem, you will show the execution of the minimum spanning tree algorithms that...

    3. In this problem, you will show the execution of the minimum spanning tree algorithms that you studied in class on the following graph: START 10 40 5 20 35 15 6 30 62 12 (a) (5 points) Trace the execution of Prim's algorithm to find the minimum spanning tree for this graph. At each step, you should show the vertex and the edge added to the tree and the resulting values of D after the relaxation operation. Use START...

  • You will be implementing a Breadth-First Search (BFS) and a Depth-First Search (DFS) algorithm on a...

    You will be implementing a Breadth-First Search (BFS) and a Depth-First Search (DFS) algorithm on a graph stored as an adjacency list. The AdjacencyList class inherits from the Graph class shown below. class Graph { private: vector _distances; vector _previous; public: Graph() { } virtual int vertices() const = 0; virtual int edges() const = 0; virtual int distance(int) const = 0; virtual void bfs(int) const = 0; virtual void dfs(int) const = 0; virtual void display() const = 0;...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT