Taene's

C++ 달팽이 문제 본문

C++ 개념 공부

C++ 달팽이 문제

taene_ 2023. 8. 25. 15:39
#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;
	}
}

enum DIR	//시계방향
{
	RIGHT = 0,
	DOWN = 1,
	LEFT = 2,
	UP = 3,
};

bool CanGO(int y, int x)
{
	if (y < 0 || y >= N)
		return false;
	if (x < 0 || x >= N)
		return false;
	if (board[y][x] != 0)
		return false;
	return true;
}

void SetBoard()
{
	int dir = RIGHT;
	int num = 1;
	int y = 0;
	int x = 0;

	while (true)
	{
		board[y][x] = num;

		if (num = N * N)
		{
			break;
		}

		int nextY, nextX;

		//int dy[] = {0,1,0,-1};
		//int dx[] = {1,0,-1,0};

		//int nextY = y + dy[dir];	아래 switch문과 같음
		//int nextX = x + dy[dir];
		switch (dir)	//바라보는 방향으로 진행
		{
		case RIGHT:
			nextY = y;
			nextX = x + 1;
			break;
		case DOWN:
			nextY = y + 1;
			nextX = x;
			break;
		case LEFT:
			nextY = y;
			nextX = x - 1;
			break;
		case UP:
			nextY = y - 1;
			nextX = x;
			break;
		}

		if (CanGO(nextY, nextX))
		{
			y = nextY;
			x = nextX;
			num++;
		}
		else
		{
			//dir = (dir+1)%4;	아래 switch문과 같음
			switch (dir)	//고개를 돌린다
			{
			case RIGHT:
				dir = DOWN;
				break;
			case DOWN:
				dir = LEFT;
				break;
			case LEFT:
				dir = UP;
				break;
			case UP:
				dir = RIGHT;
				break;
			}
		}
	}
}

int main()
{
	cin >> N;
	PrintBoard();
}

'C++ 개념 공부' 카테고리의 다른 글

[C++] string (문자열)  (0) 2023.09.02
C++ 연산자 오버로딩  (0) 2023.08.26
C++ 로또 번호 생성기  (0) 2023.08.25
C++ 포인터 관련  (0) 2023.08.25
C++ strlen(), strcpy(), strcat() 함수 만들기  (0) 2023.08.25