I have a question concerning recursion and its possibility to be transformed into a simple cycle. I am creating this game in C and I am using an already created function to manage the control the program has to do on the grill (the game is connect4) to see if there's a winning sequence but the function call itself multiple time and I can't really understand how this works. could someone please explain me how, in this specific case, the function works and how the values change at each recursion call? or, if it's easier for you, could you modify the code, replacing the recursion with simple for or while cycles? thank you very much
/*R==6 C=7, g == 1 || 2 (it depends on the player who's playing 1==player1 2==player2, r==value from 0 to 5, it depends on where the player put the token/coin, if the player wants to put a coin on column 2 where there's already another coin in m[5][2] then r is 4 and so on, c== column chosen by the player can be from 0 to 6 and e==1)
If the program finds 4 equal coins (coin value 1 and 2) in the same direction the player with that coin wins.)
int controllaF(int m[R][C], const int g, const int r, const int c, const int e){
int x, ret=0, i, ok;
printf("r=%d c=%d",r,c);
//diagonal control \ ___
if(exists(r,c) && m[r-1][c-1]==g)
if((x=controllaF(m,g,r-1,c-1,e))!=0)
ret=ret||x;
if(r<R-(NGV-1) && c<C-(NGV-1)){
ok=1;
for(i=0; i<NGV && (ok*=(m[r][c]==m[r+i][c+i] || m[r+i][c+i]==vI)); i++) ;
if(ok){
if(e)
for(i=0; exists(r+i, c+i) && m[r+i][c+i]==g; i++)
m[r+i][c+i]=vI;
ret=1;
}
}
//diagonal control / ___
if(exists(r+1,c-1) && m[r+1][c-1]==g)
if((x=controllaF(m,g,r+1,c-1,e))!=0)
ret=ret||x;
if(r>(NGV-2) && c<C-(NGV-2)){
ok=1;
for(i=0; i<NGV && (ok*=(m[r][c]==m[r-i][c+i]) || m[r-i][c+i]==vI); i++) ;
if(ok){
if(e)
for(i=0; exists(r-i, c+i) && m[r-i][c+i]==g; i++)
m[r-i][c+i]=vI;
ret=1;
}
}
//line control
if(exists(r,c-1) && m[r][c-1]==g)
if((x=controllaF(m,g,r,c-1,e))!=0)
ret=ret||x;
if(c<C-(NGV-1)){
ok=1;
for(i=0; i<NGV && (ok*=(m[r][c]==m[r][c+i] || m[r][c+i]==vI)); i++) ;
if(ok){
if(e)
for(i=0; exists(r, c+i) && m[r][c+i]==g; i++)
m[r][c+i]=vI;
ret=1;
}
}
//column control
if(r<R-(NGV-1)){
ok=1;
for(i=0; i<NGV && (ok*=(m[r][c]==m[r+i][c] || m[r+i][c]==vI)); i++) ;
if(ok){
if(e)
for(i=0; i<NGV; i++)
m[r+i][c]=vI;
ret=1;
}
}
return ret;
}
int exists(int r, int c){
// printf("\nC=%d\n", c);
if(r>=0&&r<R && c>=0&&c<C)
printf("\nC=%d\n", c);
return 1;
return 0;
}