Originally Posted by
goofy26
I've put that in but now i get an error saying stack overflow
A stack overflow occurs in endless recursion. That's because you actually didn't change the array.
You might want to isolate the minimum function and work with it in it's own program. I just did that and realized a couple of things that needed changing for it to work:
Code:
#include <stdio.h>
void showray (int ray[3][3]) { /* for debugging */
int i;
puts("-----");
for (i=0;i<3;i++) printf("%d %d %d\n",ray[i][0],ray[i][1],ray[i][2]);
}
int minimum(int array1[3][3]){
int i; /* i counter */
int j; /* j counter */
int r; /* used for return value */
int M=9999; /* initialise to the highest possible distance */
showray(array1);
/* loop through rows of distance */
for (i=0; i < 3; i++){
/*loop through columns of distance */
for (j=0; j < 3; j++){
if ((array1[i][j]<M) && (array1[i][j]!=0)){
M=array1[i][j];
array1[i][j]=0; /* oops! */
r=minimum(array1); /* reuse int j */
if (r==9999) return M; /* this will only happen once */
else return r;
}
}
}
return M;
}
int main() {
int array1[3][3]={{ 0,113,303}, {113, 0,196}, {303,196, 0}};
printf("\nfinal return: %d\n",minimum(array1));
return 0;
}
Notice the use of nested brackets when doing this multiple truth test!
If you don't actually change array1, this is just the same thing over and over.
r=9999 was a typo from my previous post, sorry.
After that, you can go straight into the recursion (no more flag). If you want to start with the highest or lowest value and progress that way, that will be more complicated -- but it might allow you to return the real lowest value in the end, which this just finishes with the last value changed in the matrix:
Code:
[root~/C] ./a.out
-----
0 113 303
113 0 196
303 196 0
-----
0 0 303
113 0 196
303 196 0
-----
0 0 0
113 0 196
303 196 0
-----
0 0 0
0 0 196
303 196 0
-----
0 0 0
0 0 0
303 196 0
-----
0 0 0
0 0 0
0 196 0
-----
0 0 0
0 0 0
0 0 0
final return: 196
However, I think it would be easier to just leave it as is and use a global variable to get the lowest value (if you need it).
On the other hand, getting the absolute lowest value each time would be truer to your original intentions. I think to do that you will have to put the flag back in, and TWO more variables to keep the i and j coordinates of M, then set the M location to zero (instead of just setting the first one found).