Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 그리디
- 구현
- Network
- 세그먼트 트리
- 시뮬레이션
- BFS
- JUnit 5
- 위상정렬
- 플로이드-와샬
- CS
- 완전탐색
- 스택
- java
- 알고리즘
- 백트래킹
- 프로그래머스
- 동적계획법
- Kotlin
- 이분탐색
- dfs
- Effective Java
- 수학
- 에라토스테네스의 체
- 투 포인터
- 백준
- 문자열
- 유니온 파인드
- 후니의 쉽게 쓴 시스코 네트워킹
- swea
- mst
Archives
반갑습니다!
[프로그래머스] 길 찾기 게임 본문
풀이
주어진 좌표를 이용해서 트리를 만든 뒤 전위순회, 후휘순회를 통해 답을 출력하는 문제이다. 문제의 핵심은 트리를 생성하는 것인데 y
값을 기준으로 내림차순으로 정렬하는데 같은 y
값을 가진 점들은 x
값을 기준으로 오름차순하여 정렬하면 root
노드부터 root
의 왼쪽 자식노드, root
의 오른쪽 자식 노드 ... 순서로 정렬된다. 노드들을 정렬하고나면 x값을 기준으로 실제 트리를 만들어주면 된다.
코드
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> pre, post;
struct Node {
int x, y, idx;
Node* left = NULL;
Node* right = NULL;
};
bool cmp(pair<pair<int, int>, int>& a, pair<pair<int, int>, int>& b) {
return a.first.second == b.first.second ? a.first.first < b.first.first : a.first.second > b.first.second;
}
// 트리에 노드를 삽입하는 함수
void insertNode(Node* root, int x, int y, int idx) {
// 트리를 순회하면서 x값 비교를 하기 위한 기준노드
Node* tmp = root;
while (true) {
if (tmp->x > x) {
if (tmp->left != NULL)
tmp = tmp->left;
else {
Node* newNode = new Node();
newNode->x = x;
newNode->y = y;
newNode->idx = idx;
tmp->left = newNode;
break;
}
}
else if (tmp->x < x) {
if (tmp->right != NULL)
tmp = tmp->right;
else {
Node* newNode = new Node();
newNode->x = x;
newNode->y = y;
newNode->idx = idx;
tmp->right = newNode;
break;
}
}
}
}
void preOrder(Node* cur) {
pre.push_back(cur->idx);
if (cur->left != NULL) preOrder(cur->left);
if (cur->right != NULL) preOrder(cur->right);
}
void postOrder(Node* cur) {
if (cur->left != NULL) postOrder(cur->left);
if (cur->right != NULL) postOrder(cur->right);
post.push_back(cur->idx);
}
vector<vector<int>> solution(vector<vector<int>> nodeinfo) {
vector<vector<int>> answer;
vector<pair<pair<int, int>, int>> nodes;
// nodeinfo에서 idx값도 포함하여 nodes 배열에 저장
for (int i = 0; i < nodeinfo.size(); i++)
nodes.push_back({ {nodeinfo[i][0], nodeinfo[i][1]}, i + 1 });
sort(nodes.begin(), nodes.end(), cmp);
// nodes[0]은 루트 노드
Node* root = new Node();
root->x = nodes[0].first.first;
root->y = nodes[0].first.second;
root->idx = nodes[0].second;
// nodes[1]부터 트리에 노드를 삽입
for (int i = 1; i < nodes.size(); i++)
insertNode(root, nodes[i].first.first, nodes[i].first.second, nodes[i].second);
preOrder(root);
postOrder(root);
answer.push_back(pre);
answer.push_back(post);
return answer;
}
'알고리즘 문제 풀이' 카테고리의 다른 글
[프로그래머스] 예상 대진표 (0) | 2020.04.16 |
---|---|
[프로그래머스] 프렌즈4블록 (0) | 2020.04.16 |
[프로그래머스] 입국심사 (0) | 2020.04.15 |
[프로그래머스] 예산 (0) | 2020.04.14 |
[프로그래머스] 블록 이동하기 (0) | 2020.04.13 |