본문 바로가기
Coding Test/Programmers

[Programmers] (월간 코드 챌린지 시즌1) Lv 2. 삼각 달팽이

by song.ift 2023. 7. 28.

https://school.programmers.co.kr/learn/courses/30/lessons/68645

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

#include <string>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;

vector<int> solution(int n) {
    vector<vector<int>> vec;
    const size_t size = n * (n + 1) / 2;    // n = 4 => 1+2+3+4 = 10
    size_t row = 0, col = 0, count = 1;

    /*
        n = 4 일 때 다음 배열을 먼저 생성
        [
          [0],
          [0, 0],
          [0, 0, 0],
          [0, 0, 0, 0],
        ]
    */
    vec.resize(n);
    for (size_t i = 0; i < n; ++i) 
        vec[i].resize(i + 1);

    while (count <= size)
    {
        // down
        {
            while (row < n && col < n && !vec[row][col])
                vec[row][col] = count++, ++row;

            --row, ++col; // 다음 좌표로 이동
        }

        // right
        {
            while (row < n && col < n && !vec[row][col])
                vec[row][col] = count++, ++col;

            col -= 2, --row; // 다음 좌표로 이동
        }

        // left diagonal
        {
            while (row < n && col < n && !vec[row][col])
                vec[row][col] = count++, --row, --col;

            row += 2, ++col; // 다음 좌표로 이동
        }
    }

    return ::accumulate(vec.begin(), vec.end(), vector<int>(), [&](auto& acc, const auto& v) {
        acc.insert(acc.end(), v.begin(), v.end());
        return acc;
    });
}

GitHub : https://github.com/developeSHG/Algorithm-Baekjoon_Programmers/commit/3d2674ec1ff7dd5e925051cd4101698457fe39b8

 

[level 2] Title: 삼각 달팽이, Time: 499.93 ms, Memory: 107 MB -BaekjoonHub · developeSHG/Algorithm-Baekjoon_Programmers@3d

developeSHG committed Jul 28, 2023

github.com

 

댓글