백준 1913번: 달팽이

danbibibi·2022년 10월 15일
0

문제

문제 바로가기> 백준 1913번: 달팽이

풀이

상 우 하 좌 방향으로 나아가야 하는 칸이 1 1 2 2 3 3 4 4 ... 와 같이 증가하므로 d%2가 0일 때마다 나아가야 하는 칸(cnt)을 한칸 씩 늘려주었다!

#include<iostream>
#define MAX 1000
using namespace std;

int N, NUM;
int map[MAX][MAX];
int dy[] = { -1, 0, 1, 0 }; // 상 우 하 좌 
int dx[] = { 0, 1, 0, -1 };

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0);
	cin >> N >> NUM;

	int idx = 2, cnt = 0;
	int y = N / 2, x = N / 2;
	pair<int, int> pos = { y + 1, x + 1 };
	map[y][x] = 1;
	for (int d = 0; y!=-1; d++) {
		d %= 4;
		if (d % 2 == 0) cnt++;
		for (int i = 0; i < cnt; i++) {
			y += dy[d];
			x += dx[d];
			if (y < 0) break;
			map[y][x] = idx++;
			if (map[y][x] == NUM) pos = { y+1, x+1 };
		}
	}

	for (int i = 0; i < N; i++) {
		for (int j = 0; j < N; j++) cout << map[i][j] << " ";
		cout << "\n";
	}
	cout << pos.first << " " << pos.second;
}
profile
블로그 이전) https://danbibibi.tistory.com

0개의 댓글