/* The following can be compiled and executed in
* visual C++ 6.0 sp6 */
#include "stdio.h"
#define MAX_AM 100
int helixMatrix[MAX_AM][MAX_AM]; // global variable
/*
*(mt_x,mt_y): coordinate of the 1st element
* start:the value of 1st element
* n: the size of the helixMatrix
*/
void SethelixMatrix(int mt_x, int mt_y, int start, int n)
{
int i, j;
if (n <= 0) //the qualification of end for the recursion
return;
if (n == 1)
{ //the extreme size of helixMatrix : 1
helixMatrix[mt_x][mt_y] = start;
return;
}
for (i = mt_x; i < mt_x + n-1; i++) //the top of the matrix
{
helixMatrix[mt_y][i] = start++;
}
for (j = mt_y; j < mt_y + n-1; j++) // the right of it
{
helixMatrix[j][mt_x+n-1] = start++;
}
for (i = mt_x+n-1; i > mt_x; i--) //the bottom of it
{
helixMatrix[mt_y+n-1][i] = start++;
}
for (j = mt_y+n-1; j > mt_y; j--) //the left of it
{
helixMatrix[j][mt_x] = start++;
}
SethelixMatrix(mt_x+1, mt_y+1, start, n-2); // the recursion
}
void main()
{
int i, j;
int n;
printf(" Input the size you want");
printf("\n\t");
scanf("%d", &n);
SethelixMatrix(0, 0, 1, n);
//print the helixMatrix
for(i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
printf("%4d", helixMatrix[i][j]);
printf("\n");
}
}