이쿠의 슬기로운 개발생활

함께 성장하기 위한 보안 개발자 EverNote 내용 공유

코딩테스트

[프로그래머스][C++] 삼각 달팽이

이쿠우우 2022. 4. 15. 19:03
반응형

 

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


글쓴이의 답


개인적인 풀이 임으로
이것보다 더 좋은 알고리즘은 많음...
이렇게도 풀이하는구나.. 공유하기 위해 올림...

#include <string>
#include <vector>
#include <stdio.h>

using namespace std;

vector<int> solution(int n) {
	vector<int> answer;
	vector<vector<int>> result;

	int total = 0;
	for (int i = 0; i < n; i++) {
		total += i + 1;
		vector<int> temp;
		result.push_back(temp);
	}

	int location = 1;
	int upCount = 0;
	int downCount = -1;
	bool MorP = true;
	int start = 1;
	int end = n;
	bool checkEnd = true;
	bool checkStart = true;
	for (int i = 1; i <= total; i++) {
		

		if ((end == location) && (checkEnd == true)) {
			if (result[location - 1].size() > 1) {
				vector<int>::iterator it = result[location - 1].end();
				result[location - 1].insert(it - upCount, i);
			}
			else {
				result[location - 1].push_back(i);
			}
		}
		else {
			if (true == MorP){
				if (result[location - 1].size() > 1) {
					vector<int>::iterator it = result[location - 1].begin();
					result[location - 1].insert(it + downCount, i);
				}
				else {
					result[location - 1].push_back(i);
				}
			}
			else {
				if (result[location - 1].size() > 1) {
					vector<int>::iterator it = result[location - 1].end();
					result[location - 1].insert(it - (upCount-1), i);
				}
				else {
					result[location - 1].push_back(i);
				}
			}
			
		}

		

		if ((end == location) && (checkEnd == true)) {			
			if (result[location-1][0] > result[location - 1].size()) {	
				continue;
			}
			else {
				MorP = false;
				end--;
				checkEnd = false;
				checkStart = true;
				upCount++;
			}
		}
		else if( ((start == location) && (checkStart == true)) || (result[location - 1][0] == result[location - 1].size())) {
							
			if ((start == location) && (checkStart == true)) {
				downCount++;
			}
			MorP = true;
			checkEnd = true;
			checkStart = false;
			start++;
		}		
		

		if (true == MorP) {
			location++;
		}
		else {
			location--;
		}
	}
    
    for(vector<int> temp : result){
        answer.insert(answer.end(), temp.begin(), temp.end());
    }
    

	return answer;
}





꾸준히 하다보면 실력이 늘겠지..

반응형