프로그래머스

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

programmers.co.kr

출처 - 프로그래머스: https://school.programmers.co.kr/learn/courses/30/lessons/68645

문제의 설명대로 n=5가 주어졌을 때 만들어지는 2차원 배열은 아래와 같다.

1        
2 12      
3 13 11    
4 14 15 10  
5 6 7 8 9

 

위 표를 자세히 보면 아래와 규칙을 가진다는 것을 알 수 있다.

이를 구현하기 위해 int형 flag를 선언하여 0이면 위에서 아래로, 1이면 왼쪽에서 오른쪽으로, 2면 우하단에서 좌상단으로 가도록하며 좌상단 top = 1, 좌하단 bottom  = n, 왼쪽 left = 1, 오른쪽 right = 0을 각각 선언하여 이를 기반으로 num이 (n x (n+1)) / 2이하일 때까지 조건에 맞춰 반복하도록 하였

이후 완성된 2차원 배열을 1차원 배열 answer에 담고 리턴하였다.

#include <string>
#include <vector>
 
using namespace std;
 
vector<int> solution(int n) {
    vector<vector<int>> v(n + 1, vector<int>(n + 1));
    vector<int> answer;
    
    int top = 1; int bottom = n; int left = 1; int right = 0;
    int max = (n * (n + 1)) / 2;
    int num = 1;
    int flag = 0;
    
    while(num <= max) {
        if(flag == 0) {
            for(int i = top; i <= bottom; i++) v[i][left] = num++;
            top++;
            left++;
            flag = 1;
        }
        else if(flag == 1) {
            for(int i = left; i <= bottom - right; i++) v[bottom][i] = num++;
            bottom--;
            flag = 2;
        }
        else if(flag == 2) {
            for(int i = bottom; i >= top; i--) v[i][i - right] = num++;
            right++;
            top++;
            flag = 0;
        }
    }
 
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++)
            answer.push_back(v[i][j]);
    }
    
    return answer;
}

+ Recent posts