Question
This is my dijkstra's algorithms code how do I modify it to Prime's algorithms code in C language please #include #include // Create an CONSTANCE
This is my dijkstra's algorithms code how do I modify it to Prime's algorithms code in C language please
#include
#include
// Create an CONSTANCE variable for INFINITY and MAX
#define INFINITY 9999
#define MAX 100
void dijkstra(int graph[MAX][MAX],int length,int startnode);
// Method for dijkstra's algorithms
void dijkstra(int graph[MAX][MAX],int length,int startnode){
//Create a variable that need to be use for this function
int cost[MAX][MAX];
int distance[MAX];
int pred[MAX];
int visited[MAX];
int count;
int mindistance;
int nextnode;
int i;
int j;
//for loop through the graph
for(i=0;i for(j = 0; j < length; j++){ //If the graph is 0 set it to infinity if(graph[i][j] == 0){ cost[i][j] = INFINITY; }else{ //else set the cost graph equalt to the graph value cost[i][j] = graph[i][j]; } }//end for 1st for loop }//end second 2st for loop for(i = 0; i < length; i++){ distance[i] = cost[startnode][i]; pred[i] = startnode; visited[i] = 0; }//end for loop distance[startnode] = 0; visited[startnode] = 1; count = 1; while(count < length - 1){ mindistance = INFINITY; for(i = 0; i < length; i++){ if(distance[i] < mindistance&&!visited[i]){ mindistance = distance[i]; nextnode = i; } visited[nextnode] = 1; for(i = 0;i < length; i++){ if(!visited[i]){ if(mindistance+cost[nextnode][i] < distance[i]){ distance[i] = mindistance + cost[nextnode][i]; pred[i] = nextnode; } } } count++; }//end for loop }//end while loop // Find the distance of each node for(i = 0;i < length; i++){ if(i != startnode){ printf(" Distance of node%d=%d",i,distance[i]); printf(" Path=%d",i); j = i; do{ j = pred[j]; printf("<-%d",j); }while(j != startnode); } }printf(" "); // print empty line } // Main Function of the code int main(){ // Create a variable for the length of the matrix, the graph, and the starting node int graph[MAX][MAX]; int length; int startingNode; // Ask the use for the length of the matrix printf("Enter the length of the matrix:"); scanf("%d",&length); // Ask the user for the starting node printf(" Enter the starting node:"); scanf("%d",&startingNode); // Ask the user to input the matrix printf(" Enter the adjacency matrix: "); // Scan the input of the matrix for(int i = 0; i < length; i++){ for(int j = 0; j < length; j++){ scanf("%d", &graph[i][j]); } } // Run the algorithm's method dijkstra(graph,length,startingNode); //return 0 return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started