[C++]_S14-연습문제(달팽이)

신치우·2025년 2월 20일

CPP

목록 보기
42/62

숫자를 입력받고(N) 해당 숫자의 크기에 해당하는 테이블을 만든 후 (NxN) 순회하며 숫자를 채우는 달팽이 모양을 만들어라

ex)
input = 5
01 02 03 04 05
16 17 18 19 06
15 24 25 20 07
14 23 22 21 08
13 12 11 10 09

#include <iostream>
#include <iomanip>
using namespace std;

const int MAX = 100;
int board[MAX][MAX] = {};
int N;

void PrintBoard()
{
	for (int y = 0; y < N; y++)
	{
		for (int x = 0; x < N; x++)
		{
			cout << setfill('0') << setw(2) << board[y][x] << " ";
		}
		cout << endl;
	}
}

void SetBoard()
{
	// 1 2 3 4 5
	//         6
	//         7
	//         8
	//         9
	// 위처럼 달팽이 모양으로 돌아가는 수식을 만들기
	int num = 0; // direction
	int y = 0;
	int x = 0;
	int cnt = 1;
	
	while (true)
	{
		switch (num)
		{
		case 0: // 오른쪽
			while (x < N && board[y][x] == 0)
			{
				board[y][x] = cnt;
				x++;
				cnt++;
			}
			y++;
			x--;
			break;
		case 1: // 아래로
			while (y < N && board[y][x] == 0)
			{
				board[y][x] = cnt;
				y++;
				cnt++;
			}
			x--;
			y--;
			break;
		case 2: // 왼쪽
			while (x >= 0 && board[y][x] == 0)
			{
				board[y][x] = cnt;
				x--;
				cnt++;
			}
			y--;
			x++;
			break;
		case 3:
			while (y >= 0 && board[y][x] == 0)
			{
				board[y][x] = cnt;
				y--;
				cnt++;
			}
			x++;
			y++;
			break;
		default:
			break;
		}
		num++;
		num %= 4;

		/*if (x != 0 && y != 0) {
			if (board[y-1][x] != 0 && board[y][x-1] != 0 && board[y+1][x] != 0 && board[y][x+1] != 0) {
				board[y][x] = cnt;
				break;
			}
		}*/
		if (cnt == N * N) {
			board[y][x] = cnt;
			break;
		}
	}

}

int main()
{
	cin >> N;

	SetBoard();
	PrintBoard();

	return 0;
}
profile
https://shin8037.tistory.com/

0개의 댓글