I wanted to build a spiral square matrix using recursion. I am able to build spiral square matrix using iterative method as below:
void main()
{
int i
#include <stdio.h>
void build_matrix(int msize, int a[msize][msize], int size, int value){
int i, row, col;
if(size < 1)
return;
row = col = (msize - size) / 2;
if(size==1){
a[row][col] = value;
return;
}
for(i=0;i<size-1;++i)
a[row][col++] = value++;//RIGHT
for(i=0;i<size-1;++i)
a[row++][col] = value++;//DOWN
for(i=0;i<size-1;++i)
a[row][col--] = value++;//LEFT
for(i=0;i<size-1;++i)
a[row--][col] = value++;//UP
build_matrix(msize, a, size-2, value);
}
int main(){
int size;
printf("input size : ");
scanf("%d", &size);
int a[size][size];
build_matrix(size, a, size, 1);
for(int r=0;r<size;++r){
for(int c=0;c<size;++c)
printf("%3d ", a[r][c]);
printf("\n");
}
return 0;
}
Working Code, without divide and Just recurse:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define N 20
bool s[N][N] = {0};
int counter;
typedef enum {
right = 0,
down,
left,
up
}c_flag;
c_flag flag;
int build_matrix(int a[N][N],int i,int j, c_flag flag)
{
int ret;
if (i < 0 || i>=N || j < 0 || j >= N || s[i][j] == true)
return false;
if(s[i][j] == false && a[i][j] == 0)
{
s[i][j] = true;
a[i][j] = ++ counter;
}
if (flag == right)
ret = build_matrix(a,i,j+1,right);
flag = down;
if (flag == down)
ret =build_matrix(a,i+1,j,down);
flag = left;
if (flag == left)
ret = build_matrix(a,i,j-1,left);
flag = up;
if (flag == up)
ret = build_matrix (a,i-1,j,up);
flag = right;
if (flag == right)
ret = build_matrix(a,i,j+1,right);
return false;
}
int main()
{
int i, j;
int k, ret;
//printf("Enter N to construct square matrix \n");
//scanf("%d",&n);
int a[N][N] = {0};
k = N/2 + N%2;
build_matrix(a,i,i,right);
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
if (!(a[i][j] < 100))
printf("%3d ",a[i][j]);
else if(a[i][j] < 10)
printf("00%d ",a[i][j]);
else
printf("0%d ",a[i][j]);
}
printf("\n");
}
return 0;
}