카테고리 없음
[프로그래머스] 삼각 달팽이
쪼르뚜
2024. 8. 28. 19:05
728x90
반응형
🔗 문제 링크
https://school.programmers.co.kr/learn/courses/30/lessons/68645
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
반응형
728x90
👩💻 코드
#include <vector>
using namespace std;
vector<int> solution(int n) {
vector<vector<int>> triangle(n, vector<int>(n));
vector<int> answer;
int dx[3] = {1, 0, -1};
int dy[3] = {0, 1, -1};
int x = 0;
int y = 0;
int direction = 0;
for (int i = 1; i <= n * (n + 1) / 2; i++) {
triangle[x][y] = i;
int nx = x + dx[direction];
int ny = y + dy[direction];
if (nx >= n || ny >= n || nx < 0 || ny < 0 || triangle[nx][ny] != 0) {
direction = (direction + 1) % 3;
nx = x + dx[direction];
ny = y + dy[direction];
}
x = nx;
y = ny;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
answer.push_back(triangle[i][j]);
}
}
return answer;
}
📝 풀이
n x n 크기의 vector를 초기화 합니다.
dx와 dy에 아래,오른쪽, 대각선 위로 이동할 수 있도록 값을 초기화 합니다.
1부터 마지막 숫자까지 반복문을 돌며 다음 위치가 좌표를 벗어나거나 이미 숫자가 채워져있다면 방향을 전환합니다.
마지막 숫자는 1부터 n까지 더한 값(n * (n+1) / 2)입니다.
최종 결과를 answer에 push하여 return 합니다.
728x90
반응형