C언어; 달팽이 배열 이해하기

달팽이 배열 문제 설명

문제

  • 달팽이 배열을 만들어서 이를 출력하는 프로그램을 작성하고자 한다.
    여기서 말하는 달팽이 배열은 다음과 같다

예시

  • 4x4 배열
1   2   3   4

12  13  14  5

11  16  15  6

10  9   8   7
  • 5x5 배열
1   2   3   4   5

16  17  18  19  6

15  24  25  20  7

14  23  22  21  8

13  12  11  10  9

요구사항

  1. 프로그램 사용자로부터 하나의 숫자 n을 입력받는다.
  2. 입력된 n에 해당하는 n * n 크기의 달팽이 배열을 생성한다.
  3. 달팽이 배열을 출력하는 프로그램을 작성하시오.

입/출력 예시

  • 입력 예시
4
  • 출력 예시
1   2   3   4

12  13  14  5

11  16  15  6

10  9   8   7

코드 분석

직관적으로 구현하는 것에 의의를 두므로 함수에서 출력만 할 것입니다.

step 1) 배열 선언 - 동적할당

int **array = (int **)malloc(size * sizeof(int *));
for (int i = 0; i < size; i++)
    array[i] = (int *)malloc(size * sizeof(int));

 

동적할당 관련 설명 생략.

step 2) 반복문의 조건은?

while (value <= size * size)

 

달팽이 배열에서 순서대로 증가하는 수가 value 이다. 이때, value 의 최댓값은 n*n 크기 배열의 요소의 최대 개수와 같다.(즉, value의 최댓값은 n*n)

 

while문 안에 반복문이 4개가 존재하도록 코드를 머릿속에서 생각하고 접근하였음.(방향 별로 4개의 섹션으로 구분하여 처리할 생각)

행과 열을 구분해서 while안의 4개의 반복문을 컨트롤.

 

전체 코드

#include <stdio.h>
#include <stdlib.h>

void snailArr(int size)
{
    int **array = (int **)malloc(size * sizeof(int *));
    for (int i = 0; i < size; i++)
        array[i] = (int *)malloc(size * sizeof(int));

    int value = 1;
    int row = 0, col = 0;
    int minRow = 0, maxRow = size - 1;
    int minCol = 0, maxCol = size - 1;

    while (value <= size * size)
    {
        for (col = minCol; col <= maxCol; col++)
            array[minRow][col] = value++;
        minRow++;

        for (row = minRow; row <= maxRow; row++)
            array[row][maxCol] = value++;
        maxCol--;

        for (col = maxCol; col >= minCol; col--)
            array[maxRow][col] = value++;
        maxRow--;

        for (row = maxRow; row >= minRow; row--)
            array[row][minCol] = value++;
        minCol++;
    }

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

    for (int i = 0; i < size; i++)
        free(array[i]);

    free(array);
}

int main()
{
    int size;
    printf("size: ");
    scanf("%d", &size);

    if (size <= 0)
        return NULL;

    snailArr(size);

    return 0;
}

댓글