Skip to content

Commit 3348673

Browse files
committed
[Week13]PGS_42892: 길찾기 게임
1 parent 572384c commit 3348673

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
package study.week13;
2+
3+
import java.util.Arrays;
4+
5+
// 길 찾기 게임
6+
// 이진 트리
7+
8+
/**
9+
* 시간복잡도: O(NlogN)
10+
* Node 클래스의 정렬 기준은 y값이 크면 부모 노드가 되며, x값 기준으로 왼쪽 자식, 오른쪽 자식이 결정된다.
11+
* n.y -this.y 로 y좌표 기준으로 내림차순 정렬합니다, this.x -n.x 는 y좌표가 같다면 x좌표 기준으로 오름차순 정렬합니다.
12+
* 정렬을 하는 이유는 1. 루트 노드를 찾기 위해, 2. 부모가 자식보다 먼저 생성되어야 하므로, 3. 트리 만들기 편해서
13+
* insertNode 를 통해 이진트리를 만듭니다. 왼쪽 자식, 오른쪽 자식인지 판별 후 비어있으면 연결, 아니면 타고 내려감
14+
* 이후 완성된 이진트리를 기반으로 전위, 후위 순회
15+
* 전위 순회 : 루트 -> 왼쪽자식 -> 오른쪽자식 순서 방문
16+
* 후위 순회 : 왼쪽 -> 오른쪽 -> 루트 순서로 방문
17+
* 문제점: 만약에 y값이 동일한데 head 인 경우(예: (3, 11), (4,11) 가 input으로 들어오면? (3,11) 의 오른쪽 자식이 (4,11) 이 된다..
18+
*/
19+
public class PGS_42892 {
20+
class Solution {
21+
static class Node implements Comparable<Node>{
22+
int v;
23+
int x;
24+
int y;
25+
Node left;
26+
Node right;
27+
Node(int v, int x, int y, Node left, Node right){
28+
this.v = v;
29+
this.x = x;
30+
this.y = y;
31+
this.left = left;
32+
this.right = right;
33+
}
34+
35+
@Override
36+
public int compareTo(Node n){
37+
if(this.y == n.y){
38+
return this.x - n.x;
39+
}
40+
41+
return n.y - this.y;
42+
}
43+
}
44+
45+
int preIdx = 0;
46+
int postIdx = 0;
47+
48+
public int[][] solution(int[][] nodeinfo) {
49+
int[][] answer = {};
50+
int size = nodeinfo.length;
51+
Node[] nodes = new Node[size];
52+
for(int i=0; i<nodeinfo.length; i++){
53+
nodes[i] = new Node(i+1, nodeinfo[i][0], nodeinfo[i][1], null, null);
54+
}
55+
56+
Arrays.sort(nodes);
57+
58+
Node parent = nodes[0];
59+
for(int i=1 ; i<size; i++){
60+
insertNode(parent, nodes[i]);
61+
}
62+
63+
answer = new int[2][size];
64+
preorder(parent, answer[0]);
65+
postorder(parent, answer[1]);
66+
67+
return answer;
68+
}
69+
70+
public void insertNode(Node parent, Node child){
71+
if(parent.x > child.x){
72+
if(parent.left == null)parent.left = child;
73+
else insertNode(parent.left, child);
74+
}else{
75+
if(parent.right == null)parent.right = child;
76+
else insertNode(parent.right, child);
77+
}
78+
}
79+
80+
public void preorder(Node node, int[] pre){
81+
if(node != null){
82+
pre[preIdx++] = node.v;
83+
preorder(node.left, pre);
84+
preorder(node.right, pre);
85+
}
86+
}
87+
88+
public void postorder(Node node, int[] post){
89+
if(node != null){
90+
postorder(node.left, post);
91+
postorder(node.right, post);
92+
post[postIdx++] = node.v;
93+
}
94+
}
95+
}
96+
}

0 commit comments

Comments
 (0)