Skip to content

Commit baa1980

Browse files
author
lloydstockman
committed
making NearestNeighbor for kd tree search properly.
It was just checking to see if the left or right tree had a better score than current but the algorithm should check to see if the planes cross our best score for the coordinate we are looking for, not if the nodes score is better or not.
1 parent d5ed099 commit baa1980

File tree

2 files changed

+8
-5
lines changed

2 files changed

+8
-5
lines changed

NetTopologySuite.Tests.NUnit/Index/KdTree/KdTreeTest.cs

-1
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,6 @@ public void TestNearestNeighbor()
6868
kd.Insert(new Coordinate(19, 12), "J");
6969
kd.Insert(new Coordinate(10, 2), "K");
7070

71-
7271
var res = kd.NearestNeighbor(new Coordinate(13, 2));
7372

7473
Assert.AreEqual("K", res.Data);

NetTopologySuite/Index/KdTree/KdTree.cs

+8-4
Original file line numberDiff line numberDiff line change
@@ -337,12 +337,10 @@ private static void NearestNeighbor(KdNode<T> currentNode,
337337
var searchLeft = false;
338338
var searchRight = false;
339339
if (currentNode.Left != null)
340-
searchLeft = (Math.Pow(currentNode.Left.X - queryCoordinate.X, 2) +
341-
Math.Pow(currentNode.Left.Y - queryCoordinate.Y, 2)) < closestDistanceSq;
340+
searchLeft = NeedsToBeSearched(queryCoordinate, currentNode.Left, closestDistanceSq);
342341

343342
if (currentNode.Right != null)
344-
searchRight = (Math.Pow(currentNode.Right.X - queryCoordinate.X, 2) +
345-
Math.Pow(currentNode.Right.Y - queryCoordinate.Y, 2)) < closestDistanceSq;
343+
searchRight = NeedsToBeSearched(queryCoordinate, currentNode.Right, closestDistanceSq);
346344

347345
if (searchLeft)
348346
{
@@ -359,6 +357,12 @@ private static void NearestNeighbor(KdNode<T> currentNode,
359357
}
360358
}
361359

360+
private static bool NeedsToBeSearched(Coordinate target, KdNode<T> node, double closestDistSq)
361+
{
362+
return node.X >= target.X - closestDistSq && node.X <= target.X + closestDistSq
363+
|| node.Y >= target.Y - closestDistSq && node.Y <= target.Y + closestDistSq;
364+
}
365+
362366
/// <summary>
363367
/// Performs a nearest neighbor search of the points in the index.
364368
/// </summary>

0 commit comments

Comments
 (0)