/***************************************************************************
 *            Snail_Algorithms.c
 *
 *  Wed Jan  2 16:45:57 2008
 *  Copyright  2008  pchero21
 *  pchero21@gmail.com
 ****************************************************************************/

/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
 
#include <stdio.h>
#include <math.h>

void array_rotation(int size, int (*array)[size]);
void snail_algorithms(int size, int (*array)[size]);

int main()
{
	int size;
	int tmp, i, j, k;
	int first, n, size_tmp;

	printf("\ninsert number : ");
	scanf("%d", &size);

	int array[size][size];
		
	snail_algorithms(size, array)	;

	for(i = 0; i < size; i++) {
		for(j = 0; j < size; j++)
			printf("%d\t", array[i][j]);
		
		putchar('\n');
	}
}

/*********************************************************************************************
 * FUNCTION : array_rotation
 * DESCRIPTION : 행렬의 방향을 90도 바꾸어 주는 함수
 *********************************************************************************************/
void array_rotation(int size, int (*array)[size])
{
	int i, j;
	int array_tmp[size][size];

	// array copy
	for(i = 0; i < size; i++)
		for(j = 0; j < size; j++)
			array_tmp[i][j] = array[i][j];

	// rotate
	for(i = 0; i < size; i++)
		for(j = 0; j < size; j++)
			array[i][j] = array_tmp[j][size - i - 1];
		
}

/*********************************************************************************************
 * FUNCTION : snail_algorithms
 * DESCRIPTION : 달팽이 알고리즘. 행렬의 숫자 배열을 달팽이 껍질처럼 입력한다.
 *********************************************************************************************/
void snail_algorithms(int size, int (*array)[size])
{
	int first;
	int number;
	int size_tmp;
	int i, j, k;

	first = 0;
	number = 1;
	k = 0;

	for(i = 0; i <= ceil(size / 2); i++) {
		for(j = 0; j < 4; j++) {
			if(first != 0)	// 행의 첫부분인지 검사
				k = i + 1;
			else	
				k = i;

			if(j % 3 == 0 && j != 0)		// 3번의 로테이션 마다 사이즈가 1씩 줄어든다.
				size_tmp = size - i - 1;
			else
				size_tmp = size - i;
			
			for(; k < size_tmp; k++) {	// 실제적으로 배열에 값을 입력하는 부분
				array[i][k] = number;
				number++;
				first = 1;
			}
		array_rotation(size, array);
		}
		first = 0;
	}
}
