Reputation: 1
I'm currently learning C and have recently written a program to find the minimum spanning tree using Prim's algorithm. This program works fine, but requires the cost of each edge (of course).
If I want to find the MST for a large number of 2D co-ordinates (e.g. 50), I need to find the Euclidian Distance Matrix for the points first. My question is: can this be done in C without computing
distance = sqrt((x2-x1)^2+(y2-y1)^2)
for every single point, for example by using loops?
I have been trying to use
arrayX[] = {x1,x2,x3,...xn}
arrayY[] = {y1,y2,y3,...yn}
and using a for
loop, though have been unable to do so due to my inexperience (if this was 1D, of course, this would be very easy!).
Can anyone give me any pointers as to what to do? Thanks in advance!
Upvotes: 0
Views: 628
Reputation: 400139
It's best to model your data clearly. For instance, if you're working with 2D points having integer coordinates, model that:
typedef struct {
int x, y;
} point2d;
Now you create an array of these:
point2d my_points[] = { { x1, y1 }, { x2, y2 }, ... };
Above x1
, y1
and so on should of course be actual integer values.
You can loop over this:
for(size_t i = 0; i < sizeof my_points / sizeof *my_points; ++i)
printf("Point %zu is at (%d,%d)\n", i, my_points[i].x, my_points[i].y);
And so on. Note that the above snippet assumes C99.
When computing distance, remember that ^
in C is bitwise XOR, not exponentiation. For the latter, use the pow()
or powf()
functions. As mentioned, if you're just going to be comparing relative distances, there's no point in computing the sqrt()
.
Upvotes: 0
Reputation: 25753
If you only need to compare the distance values and don't need the actual value, then you can skip the expensive sqrt() call. The result of comparisons will stay the same as if the call were made.
Upvotes: 1