题目正文:
http://coursera.cs.princeton.edu/algs4/assignments/kdtree.html
作业难点:
如何组织自己的数据结构是本道题的最难点,基本上有思路就肯定可以完成。题目一定要看仔细,基本上2dtree部分已经把实现原理说清楚了。
作业技巧:
1、逐步实现,实现完成后用insert、contain测试下,没问题再写draw,测试没问题再写其余的。
2、重复输入的问题不要忘了
3、range虽然api里写的是all point inside the rectangle,但是你必须把边界上的点也算进去
4、java不像C#可以传参数前面加ref或out,所以必须在递归的时候返回Point
5、比较容易疏忽的是子节点在分界线上部或者下部的处理是不一样的,你认为左边是右子树,上边是左子树都没关系。最后结果不会有问题
代码参考:
(这是我自己亲测100分的答案,不代表写得最好,请在自己实在完成不了的时候再看,不然的话做这个题目的意义一点都没有)
1 import edu.princeton.cs.algs4.Point2D; 2 import edu.princeton.cs.algs4.RectHV; 3 import edu.princeton.cs.algs4.SET; 4 5 import java.util.Stack; 6 7 8 public class PointSET { 9 private SET<Point2D> pointSet; 10 11 public PointSET() // construct an empty set of points 12 { 13 pointSet = new SET<Point2D>(); 14 } 15 16 private void checkNull(Object obj) { 17 if (obj == null) { 18 throw new NullPointerException(); 19 } 20 } 21 22 public boolean isEmpty() // is the set empty? 23 { 24 return pointSet.isEmpty(); 25 } 26 27 public int size() // number of points in the set 28 { 29 return pointSet.size(); 30 } 31 32 public void insert(Point2D p) // add the point to the set (if it is not already in the set) 33 { 34 checkNull(p); 35 pointSet.add(p); 36 } 37 38 public boolean contains(Point2D p) // does the set contain point p? 39 { 40 checkNull(p); 41 42 return pointSet.contains(p); 43 } 44 45 public void draw() // draw all points to standard draw 46 { 47 for (Point2D p : pointSet) { 48 p.draw(); 49 } 50 } 51 52 public Iterable<Point2D> range(RectHV rect) // all points that are inside the rectangle 53 { 54 checkNull(rect); 55 56 Stack<Point2D> stack = new Stack<Point2D>(); 57 58 for (Point2D p : pointSet) { 59 if ((p.x() >= rect.xmin()) && (p.x() <= rect.xmax()) && 60 (p.y() >= rect.ymin()) && (p.y() <= rect.ymax())) { 61 stack.push(p); 62 } 63 } 64 65 return stack; 66 } 67 68 public Point2D nearest(Point2D p) // a nearest neighbor in the set to point p; null if the set is empty 69 { 70 checkNull(p); 71 72 Point2D point = null; 73 74 for (Point2D setp : pointSet) { 75 if ((point == null) || 76 (p.distanceSquaredTo(point) > p.distanceSquaredTo(setp))) { 77 point = setp; 78 } 79 } 80 81 return point; 82 } 83 84 public static void main(String[] args) // unit testing of the methods (optional) 85 { 86 } 87 }