문제 링크입니다: https://programmers.co.kr/learn/courses/30/lessons/68645
코딩테스트 연습 - 삼각 달팽이
5 [1,2,12,3,13,11,4,14,15,10,5,6,7,8,9] 6 [1,2,15,3,16,14,4,17,21,13,5,18,19,20,12,6,7,8,9,10,11]
programmers.co.kr
규칙을 보면 n * (n + 1) / 2 즉, 1부터 n까지 더했을 때의 값이 삼각 달팽이의 마지막 숫자입니다.
따라서, 마지막 숫자를 입력할 때까지 회전을 시킨 뒤 answer 벡터에 순서대로 숫자를 넣어주면 되는 문제였습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <vector> | |
using namespace std; | |
const int MAX = 1000; | |
typedef struct | |
{ | |
int y, x; | |
} Dir; | |
Dir moveDir[3] = { { 1, 0 }, {0, 1}, {-1, -1} }; | |
int triangle[MAX][MAX]; | |
vector<int> solution(int n) { | |
int y = -1, x = 0; | |
int idx = 1; | |
int dir = 0; | |
while (1) | |
{ | |
if (idx == n * (n + 1) / 2 + 1) | |
{ | |
break; | |
} | |
int nextY = y + moveDir[dir].y; | |
int nextX = x + moveDir[dir].x; | |
if (nextY < 0 || nextY >= n || nextX < 0 || nextX >= n | |
|| triangle[nextY][nextX]) | |
{ | |
dir = (dir + 1) % 3; | |
continue; | |
} | |
triangle[nextY][nextX] = idx++; | |
y = nextY; | |
x = nextX; | |
} | |
vector<int> answers; | |
for (int i = 0; i < n;i++) | |
{ | |
for (int j = 0; j < n; j++) | |
{ | |
if (triangle[i][j]) | |
{ | |
answers.push_back(triangle[i][j]); | |
} | |
} | |
} | |
return answers; | |
} |

개발환경:Visual Studio 2017
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~
반응형
'알고리즘 > programmers' 카테고리의 다른 글
[Programmers] 쿼드압축 후 개수 세기 (0) | 2021.10.02 |
---|---|
[Programmers] 이진 변환 반복하기 (0) | 2021.10.02 |
[Programmers] 두 개 뽑아서 더하기 (0) | 2021.10.02 |
[Programmers] 3진법 뒤집기 (0) | 2021.10.02 |
[Programmers] 내적 (0) | 2021.10.02 |