프로그래머스 - 삼각 달팽이

well-life-gm·2021년 10월 29일
0

프로그래머스

목록 보기
7/125

프로그래머스 - 삼각 달팽이

그림

위와 같은 규칙을 가지는 삼각 달팽이를 만들어서 0행부터 순서대로 결과를 담아서 반환해주면 된다.

0
00
000
0000
00000
...
의 형태로 삼각 달팽이가 생겼다고 일반화하고, 규칙은 다음과 같다.
1. i % 3 == 0
row = row + 1, col = col

2. i % 3 == 1
row = row, col = col + 1

3. i % 3 == 2
row = row - 1, col = col - 1

이 규칙을 발견하면 그 다음부턴 금방푼다.

#include <string>
#include <vector>

using namespace std;

int rowDir[3] = { 1, 0, -1 };
int colDir[3] = { 0, 1, -1 };
vector<int> solution(int n) {
    vector<int> answer;
    vector<vector<int>> numV;
    for(int i=0;i<n;i++) {
        vector<int> tmp(i + 1, 0);
        numV.push_back(tmp);
    }

    int nrow = 0, ncol = 0;
    int cnt = 1;
    for(int i=0;i<=n;i++) {
        int end;
        end = i == 0 ? n - 1 : n - i;
        end = i == n ? 1 : end;
        for(int j=0;j<end;j++) {
            numV[nrow][ncol] = cnt++;
            nrow = nrow + rowDir[i % 3];
            ncol = ncol + colDir[i % 3];
        }
    }
    for(int i=0;i<numV.size();i++) 
        for(int j=0;j<numV[i].size();j++) 
            answer.push_back(numV[i][j]);
        
    return answer;
}

결과

profile
내가 보려고 만든 블로그

0개의 댓글