KD Tree
- 다차원 점을 저장하는 공간 탐색 트리
KD 트리 (K-Dimensional Tree)
KD 트리는 여러 좌표를 가진 점을 저장하는 이진 트리이다. 이진 탐색 트리가 매번 같은 키를 비교한다면, KD 트리는 깊이에 따라 비교할 좌표축을 바꾼다. $k$차원에서 깊이 $d$인 노드의 분할 축은 $d \bmod k$다. 루트의 깊이를 $0$으로 두면 2차원에서는 $x, y, x, y, \ldots$ 순으로, 3차원에서는 $x, y, z, x, \ldots$ 순으로 비교한다.
구현 방법
1. 중앙값으로 트리 만들기
현재 축의 좌표를 기준으로 중앙값에 해당하는 점을 루트로 고른다. 왼쪽 서브트리에는 해당 축의 좌표가 루트 이하인 점이, 오른쪽에는 루트 이상인 점이 들어간다. 같은 좌표가 여러 개 있으면 양쪽에 나뉘어 들어갈 수 있다. 두 구간에 대해 다음 축으로 넘어가 같은 과정을 반복한다.
아래 예시의 점 일곱 개를 $x$로 보면 중앙값에 해당하는 점은 $(5, 4)$이다. 왼쪽의 세 점은 $y$좌표가 $3, 4, 7$이므로 $(3, 4)$가 왼쪽 서브트리의 루트가 된다. 오른쪽 세 점의 $y$좌표는 $1, 2, 6$이므로 $(7, 2)$가 오른쪽 서브트리의 루트가 된다.
find_median은 퀵셀렉트(Quickselect)로 배열의 가운데 자리에 올 점을 고른다. 현재 축의 좌표를 피벗보다 작은 구간, 같은 구간, 큰 구간으로 나눈다. 가운데 자리가 같은 구간에 들어가면 선택을 마치고, 그 밖에 있으면 그 자리를 포함하는 구간만 다시 분할한다. make_tree는 선택한 자리를 기준으로 배열의 앞뒤를 나눈다. 노드는 입력 배열에 저장되어 있으므로 트리를 사용하는 동안 배열도 계속 살아 있어야 한다.
2. 점 탐색
point_search는 현재 점의 모든 좌표가 찾는 점과 같은지 검사한다. 다르다면 현재 분할 축만 비교한다. 찾는 좌표가 더 작거나 크면 해당 방향의 서브트리만 보면 된다. 분할 축의 좌표가 같다면 같은 좌표가 양쪽에 있을 수 있으므로, 왼쪽에서 찾지 못했을 때 오른쪽도 확인한다.
예를 들어 $(4, 7)$을 찾으려면 루트에서 $4 < 5$이므로 왼쪽으로 간다. $(3, 4)$에서는 비교 축이 $y$로 바뀌고 $7 > 4$이므로 오른쪽으로 간다. 도착한 점의 두 좌표가 모두 일치하면 탐색을 마친다.
3. 범위 탐색
range_search는 각 축의 하한과 길이로 주어진 직사각형이나 직육면체 안에 있는 점을 모은다. 현재 분할 축에서 노드의 좌표가 하한보다 작으면 왼쪽 서브트리 전체를 건너뛴다. 상한보다 크면 오른쪽을 건너뛴다. 노드의 좌표가 현재 축의 범위 안에 있다면 양쪽을 확인하고, 현재 점은 모든 축에서 범위 안에 있을 때만 결과에 넣는다. 좌표가 하한이나 상한과 같을 때도 결과에 포함한다.
예를 들어 $[6, 9] \times [3, 7]$을 찾으면 루트의 $x=5$가 하한보다 작아서 왼쪽 전체를 건너뛴다. 다음 노드 $(7, 2)$에서는 $y=2$가 하한보다 작아서 다시 오른쪽만 확인한다. 결과는 $(9, 6)$이다.
4. 최근접점 탐색
nearest_neighbor_search는 현재까지 가장 가까운 점인 bestNode와 그 점까지의 거리 제곱인 bestDist를 유지한다. 각 노드에서 후보를 갱신하고, 질의점과 같은 쪽에 있는 자식부터 확인한다. 반대편을 탐색할지는 질의점에서 분할선(3차원이라면 분할면)까지의 거리 제곱 $\Delta^2$으로 판단한다.
반대편 점에 도달하려면 현재 축에서 적어도 $\vert \Delta \vert$만큼 움직여야 한다. 따라서 $\Delta^2$이 이미 bestDist 이상이면 반대편에서는 더 가까운 점을 얻을 수 없다. 아래 코드는 같은 거리의 점이 여러 개일 때 처음 발견한 점 하나를 반환한다.
예를 들어 질의점 $(6, 7)$에서는 $x=5$의 오른쪽을 먼저 확인한다. 오른쪽을 확인한 뒤에도 가장 짧은 거리 제곱은 $10$이고, 분할선까지는 $1^2=1$이므로 왼쪽도 탐색한다. 왼쪽에서 $(4, 7)$을 찾으면 거리 제곱이 $4$로 줄어든다.
소스코드
make_tree는 중앙값을 기준으로 배열을 나눈다. 분할 축의 좌표가 같은 점도 양쪽에 배치될 수 있으므로, 점 탐색과 범위 탐색은 경계에서 양쪽을 확인한다. 범위 탐색의 결과 배열은 입력 점 개수만큼 준비한다. 이 예제는 $1 \le k \le 3$인 유한 좌표를 사용하며, 거리 제곱은 double 범위 안에 있다고 가정한다.
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#include <math.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#define MAX_DIM 3
struct kd_node_t {
double x[MAX_DIM];
struct kd_node_t *left, *right;
};
void swap(struct kd_node_t *a, struct kd_node_t *b) {
if (a == b) {
return;
}
double temp[MAX_DIM];
memcpy(temp, a->x, sizeof temp);
memcpy(a->x, b->x, sizeof temp);
memcpy(b->x, temp, sizeof temp);
}
// 반열린 구간 [start, end)에서 중앙 위치에 올 점을 고른다.
struct kd_node_t *find_median(struct kd_node_t *start,
struct kd_node_t *end, int i) {
if (start == end) {
return NULL;
}
struct kd_node_t *median = start + (end - start) / 2;
while (end - start > 1) {
double pivot = start[(end - start) / 2].x[i];
struct kd_node_t *lower = start;
struct kd_node_t *upper = end;
for (struct kd_node_t *p = start; p < upper;) {
if (p->x[i] < pivot) {
swap(p, lower);
++p;
++lower;
} else if (p->x[i] > pivot) {
--upper;
swap(p, upper);
} else {
++p;
}
}
if (median < lower) {
end = lower;
} else if (median >= upper) {
start = upper;
} else {
break;
}
}
return median;
}
struct kd_node_t *make_tree(struct kd_node_t *t, size_t len, int i, int dim) {
if (len == 0) {
return NULL;
}
struct kd_node_t *root = find_median(t, t + len, i);
size_t leftLen = (size_t)(root - t);
int next = (i + 1) % dim;
root->left = make_tree(t, leftLen, next, dim);
root->right = make_tree(root + 1, len - leftLen - 1, next, dim);
return root;
}
const struct kd_node_t *point_search(const struct kd_node_t *root,
const struct kd_node_t *nd,
int i, int dim) {
if (root == NULL) {
return NULL;
}
int axis = 0;
while (axis < dim && root->x[axis] == nd->x[axis]) {
++axis;
}
if (axis == dim) {
return root;
}
int next = (i + 1) % dim;
if (nd->x[i] < root->x[i]) {
return point_search(root->left, nd, next, dim);
}
if (nd->x[i] > root->x[i]) {
return point_search(root->right, nd, next, dim);
}
const struct kd_node_t *found = point_search(root->left, nd, next, dim);
return found != NULL ? found : point_search(root->right, nd, next, dim);
}
void range_search(const struct kd_node_t *root,
const double pos[], const double length[],
int i, int dim, const struct kd_node_t *result[], size_t *count) {
if (root == NULL) {
return;
}
int axis = 0;
while (axis < dim && pos[axis] <= root->x[axis] &&
root->x[axis] <= pos[axis] + length[axis]) {
++axis;
}
if (axis == dim) {
result[(*count)++] = root;
}
int next = (i + 1) % dim;
if (pos[i] <= root->x[i]) {
range_search(root->left, pos, length, next, dim, result, count);
}
if (root->x[i] <= pos[i] + length[i]) {
range_search(root->right, pos, length, next, dim, result, count);
}
}
double dist(const struct kd_node_t *a, const struct kd_node_t *b, int dim) {
double distance = 0;
for (int i = 0; i < dim; ++i) {
double diff = a->x[i] - b->x[i];
distance += diff * diff;
}
return distance;
}
void nearest_neighbor_search(const struct kd_node_t *root,
const struct kd_node_t *nd, int i, int dim,
const struct kd_node_t **bestNode, double *bestDist) {
if (root == NULL || *bestDist == 0) {
return;
}
double currentDist = dist(root, nd, dim);
if (currentDist < *bestDist) {
*bestDist = currentDist;
*bestNode = root;
}
double delta = nd->x[i] - root->x[i];
const struct kd_node_t *near = delta < 0 ? root->left : root->right;
const struct kd_node_t *far = delta < 0 ? root->right : root->left;
int next = (i + 1) % dim;
nearest_neighbor_search(near, nd, next, dim, bestNode, bestDist);
if (delta * delta < *bestDist) {
nearest_neighbor_search(far, nd, next, dim, bestNode, bestDist);
}
}
int main(void) {
struct kd_node_t points[] = {
{.x = {2, 3}}, {.x = {5, 4}}, {.x = {3, 4}}, {.x = {9, 6}},
{.x = {4, 7}}, {.x = {8, 1}}, {.x = {7, 2}}
};
const int dim = 2;
struct kd_node_t *root = make_tree(points, sizeof points / sizeof points[0], 0, dim);
const struct kd_node_t target = {.x = {4, 7}};
printf("point found: %d\n", point_search(root, &target, 0, dim) != NULL);
const double pos[] = {6, 3};
const double length[] = {3, 4};
const struct kd_node_t *result[sizeof points / sizeof points[0]];
size_t count = 0;
range_search(root, pos, length, 0, dim, result, &count);
for (size_t i = 0; i < count; ++i) {
printf("range: (%.0f, %.0f)\n", result[i]->x[0], result[i]->x[1]);
}
const struct kd_node_t query = {.x = {6, 7}};
const struct kd_node_t *bestNode = NULL;
double bestDist = INFINITY;
nearest_neighbor_search(root, &query, 0, dim, &bestNode, &bestDist);
if (bestNode != NULL) {
printf("nearest: (%.0f, %.0f), distance^2: %.0f\n",
bestNode->x[0], bestNode->x[1], bestDist);
}
return 0;
}
시간 복잡도
중앙 위치를 기준으로 배열을 둘로 나누므로 트리 높이는 $O(\log N)$이다. 각 중앙값을 해당 구간 크기에 비례하는 시간에 선택한다면, 한 깊이에서 처리하는 구간 크기의 합이 $N$이므로 트리 전체를 만드는 데 $O(N\log N)$이 걸린다. 위 퀵셀렉트는 피벗에 따라 선택이 한쪽으로 치우칠 수 있으므로 이 구성 시간은 최악의 경우까지 보장되지는 않는다.
차원 수를 상수로 보면 점 탐색은 매번 한쪽만 방문하는 경우 $O(\log N)$이다. 분할 좌표가 여러 번 같으면 양쪽을 방문해 최악 $O(N)$이 될 수 있다. 범위·최근접 탐색도 분할선으로 방문할 영역을 줄이지만, 범위가 전체 트리를 덮거나 최근접 후보를 찾기 위해 양쪽을 계속 확인해야 하면 최악 $O(N)$이다.
