I’m attempting to code Prim’s algorithm. However when I compile I get errors on lines: 57,59,60,62,63,65
Obviously it was something to do with my arrays… I just don’t know what exactly. I get the feeling it has to do with pointers which I have tried to figure out and have failed.
int map[][7] is a global array I am using to keep track of my initial graph.
edit – as requested here is all of the code
#include <iostream>
using namespace std;
void performPrims(int);
void print(int *);
// Global Variables
int nodes = 7;
int cur = 0;
int cost = 0;
int map[][7] =
{{0,3,6,0,0,0,0},
{3,0,7,0,0,12,0},
{6,7,0,10,13,8,0},
{0,0,10,0,0,0,5},
{0,0,13,0,0,9,4},
{0,12,8,0,9,0,11},
{0,0,0,5,4,11,0}};
int main()
{
// Initializations
srand(time(NULL));
int S = rand() % 7; // Create an arbitrary starting point
// Perform Prim's Algorithm starting with S
performPrims(S);
return 0;
}
void performPrims(int S)
{
int low = 100;
// open[] is used to keep track of what vertices are available
int open [] = {1,2,3,4,5,6,7};
// closed [] is used to keep track of what vertices have been reached and in what order
int closed [] = {0,0,0,0,0,0,0};
open [S] = 0; // Make our starting node unavailable
closed [cur] = S+1; // Record our starting node in the path
cur++;
while (cur < 7)
{
int i=0;
while (i<nodes)
{
int k=0;
while (k<nodes)
{
if (*map[*close[i]-1][k] > 0 && *map[*close[i]-1][k] < low)
{
low = map[close[i]-1][k];
close [cur] = k+1;
}
map[close[cur-1]-1][close[cur]-1] = 0;
map[close[cur]-1][close[cur-1]-1] = 0;
cost += low; low = 100;
open[close[cur]-1] = 0;
k++;
}
i++;
}
cur++;
}
print(closed);
}
void print(int *closed)
{
cout<<"The path taken was ";
for (int i=0; i<nodes; i++)
cout<<closed[i]<<" "<<endl;
cout<<"\nThe cost is "<<cost<<endl;
}
Errors
There are a few different ones:
error: pointer to a function used in arithmetic (Many Lines)
error: invalid types ‘int[7][7][int (*)(int)]’ for array subscript (Many Lines)
error: assignment of read-only location (LINE 60)
error: cannot convert ‘int’ to ‘int ()(int)’ in assignment (LINE 60)
You misspelled
closed. You typedcloseinstead.Replace all instances of
closewithclosed.Also, add
#include <cstdlib>to the top of the file.