Search code examples
c++algorithmprims-algorithm

Prim's Algorithm with matrices


I am trying to implement Prim's algorithm with C++ and matrices.

Here is my problem:

int node[] = {11, 11, 0, 11, 11, 11, 11, 11};
int nodeCon[8];

void generatePrims() {
    int cNode = 3;

    for (int i = 1; i <= 8; i++) {

        if (graph[cNode][i] != 0){

            if (node[i] > graph[cNode][i]) {
                node[i] = graph[cNode][i];
                nodeCon[i] = cNode;
                }
            }
        }
};

cNode is the starting node.

graph[][] is the 2d matrices that holds the connections.

nodeCon[] is the array that will hold the connections for the MST (which node is connected with other)

node[]= holds the cost-value for the nodeCon.

My question is how I am going to continue to the next hop? Let's say that I found the minimum connection and I will set the value cNode= minConnection how the loop is going to look? How I know that I had examine all the nodes?

Thanks in advance


Solution

  • Something like this:

    int node[]={11,11,0,11,11,11,11,11};
    int used[]={0,0,0,0,0,0,0,0,0,0};
    int nodeCon[8];
    
    void generatePrims(){
       int cNode = 3;
       int next, min_now;
       for(int i=0; i<8; ++i) {
          used[cNode] = 1;
          min_now = MAX_INT;
          for(int i=1;i<=8;i++){
             if(!used[i]){ 
                if(node[i] > graph[cNode][i]){
                   node[i] = graph[cNode][i];
                   nodeCon[i]= cNode;
                }
                if(node[i] < min_now) {
                   min_now = node[i];
                   next = i;
                }  
             } 
          }
          cNode = next;
       }
    };
    

    Also worth noting: it will be faster if instead of array 'used' you will use a list of unused vertices.