Problem statement:
Given a integer N, print N*N numbers in a N x N spiral
Detailed problem description:
http://2600hertz.wordpress.com/2010/03/20/the-mystery-spiral/
Solution: Recently posted the following code. (managed to compress it into as few as 99 lines...)
//File : spiral.c
//
//INPUT : Size of spiral (N)
//OUTPUT : Numbers printed in a N x N spiral
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void main()
{
int N;
clrscr();
//get input no. N
printf("\nEnter size of Matrix: ");
scanf("%d",&N);
//Allocate reqd. memory
int* matrix_ptr= (int*)malloc(N*N);
//Filling the Matrix spirally
int curr_val=N*N;
int* curr_ptr=matrix_ptr;
int curr_level=N;
while(curr_level>1)
{
//curr_level-1 elements horizontally
//from left to right
for(int x=0;x<curr_level-1;x++)
{
*curr_ptr=curr_val;
curr_val--;
curr_ptr++;
}
//curr_level-1 elements vertically
//from top to bottom
for(int y=0;y<curr_level-1;y++)
{
*curr_ptr=curr_val;
curr_val--;
curr_ptr+=N;
}
//curr_level-1 elements horizontally
//from right to left
for(int z=0;z<curr_level-1;z++)
{
*curr_ptr=curr_val;
curr_val--;
curr_ptr--;
}
//curr_level-1 element vertically
//from bottom to top
for(int w=0;w<curr_level-1;w++)
{
*curr_ptr=curr_val;
curr_val--;
curr_ptr-=N;
}
//Next
curr_ptr+=N+1;
curr_level-=2;
}
*curr_ptr=curr_val;
//routine to print the matrix
printf("\n\n\n\n\n");
for( int i=0;i<N;i++)
{
for( int j=0;j<N;j++)
{
printf("%d\t",*(matrix_ptr+(i*N+j)));
}
printf("\n");
}
getch();
}
Please comment on further
optimisations (if any)...