

1. 문제 링크
1913번: 달팽이
N개의 줄에 걸쳐 표를 출력한다. 각 줄에 N개의 자연수를 한 칸씩 띄어서 출력하면 되며, 자릿수를 맞출 필요가 없다. N+1번째 줄에는 입력받은 자연수의 좌표를 나타내는 두 정수를 한 칸 띄어서
www.acmicpc.net
2. 풀이
구현 문제다.
달팽이처럼 뱅글뱅글 돌면서 순회를 하는 문제다.
구현하는 방식을 알아두자.
3. 코드
#include <cstdio>
#include <algorithm>
int n, k;
int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
bool visited[1003][1003];
int arr[1003][1003];
bool movable(int r, int c, int d) {
int nr = r + dir[d][0];
int nc = c + dir[d][1];
if (nr < 1 || nr > n || nc < 1 || nc > n) return false;
if (visited[nr][nc]) return false;
return true;
}
int main() {
scanf("%d %d", &n, &k);
int r = 1, c = 1, d = 0;
std::pair<int, int> ret;
for (int cur = n * n; cur; cur--) {
if (cur == k) ret = {r, c};
arr[r][c] = cur;
visited[r][c] = true;
if (!movable(r, c, d)) d = (d + 1) % 4;
r += dir[d][0];
c += dir[d][1];
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) printf("%d ", arr[i][j]);
printf("\n");
}
printf("%d %d", ret.first, ret.second);
}
'Algorithm > BOJ' 카테고리의 다른 글
백준[1182] 부분수열의 합 (0) | 2021.11.05 |
---|---|
백준[5052] 전화번호 목록 (0) | 2021.11.04 |
백준[11003] 최솟값 찾기 (0) | 2021.10.29 |
백준[5430] AC (0) | 2021.10.29 |
백준[16234] 인구 이동 (0) | 2021.10.29 |