코딩테스트 정수를 나선형으로 배치하기
https://school.programmers.co.kr/learn/courses/30/lessons/181832?language=cpp
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 설명
양의 정수 n이 매개변수로 주어집니다. n × n 배열에 1부터 n2 까지 정수를 인덱스 [0][0]부터 시계방향 나선형으로 배치한 이차원 배열을 return 하는 solution 함수를 작성해 주세요.
제한사항
- 1 ≤ n ≤ 30
코딩테스트 정수를 나선형으로 배치하기 코드
#include <string>
#include <vector>
using namespace std;
vector<vector<int>> solution(int n) {
vector<vector<int>> answer(n, vector<int>(n, 0));
int dx[4] = {0, 1, 0, -1}; // 오른쪽, 아래, 왼쪽, 위로 이동하기 위한 방향 벡터
int dy[4] = {1, 0, -1, 0};
int direction = 0; // 현재 방향 (0: 오른쪽, 1: 아래, 2: 왼쪽, 3: 위)
int x = 0, y = 0;
for (int i = 1; i <= n * n; ++i) {
answer[x][y] = i;
int nx = x + dx[direction], ny = y + dy[direction];
if (nx < 0 || nx >= n || ny < 0 || ny >= n || answer[nx][ny] != 0) {
// 범위를 벗어나거나 이미 채워진 셀을 만났을 때 방향을 바꿉니다.
direction = (direction + 1) % 4;
nx = x + dx[direction];
ny = y + dy[direction];
}
x = nx;
y = ny;
}
return answer;
}
댓글