dimanche 15 mars 2015

How to fill in a matrix recursively in c++?


So I have to fill in a square matrix recursively. For size N=5, it should be:



1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1


but my program shows:



1 1 1 1 1
1 2 2 2 1
1 2 3 3 1
1 2 2 2 1
1 1 1 1 1

void llenar5 (int** mat, int n, int f=0, int c=0,int k=2)
{
if (f<n)
{
if (c<n)
{
if (f==0 ||c==0||f==n-1||c==n-1)
{
*(*(mat+f)+c)=1;
llenar5(mat,n,f,c+1,k); //move to the right
}
else if (f==k-1 ||c==k-1||f==n-k||c==n-k)
{
*(*(mat+f)+c)=k;
llenar5(mat,n,f,c+1,k++);
}
}
llenar5(mat,n,f+1,c,k);
}


}


I am creating a matrix in dynamic memory, and I tried calling the function llenar5(mat,n,f+1,c+1,k+1) to jump a column and row while incrementing the values.




Aucun commentaire:

Enregistrer un commentaire