Java算出两个坐标间所有的点,并补齐点保证BFS可

这几天工作遇到了一个问题。 一个区域做分割,两个点连成一个连线后,需要算出分成两个区域后的每个区域的面积。 算面积需要BFS八个方向,所以需要保证连的线必须是封闭,且形成后的区域的点,八个方向都搜不到另一个区域去。 所以这个时候需要把 线变得更加“厚”一点,因为之前的做法一条斜线是一定能从斜上方过去的。

public ArrayList<Integer> getLineValue(Point p1, Point p2) { ArrayList<Point> splitLine = new ArrayList<>(); int dx = p2.x – p1.x; int dy = p2.y – p1.y; int absX = Math.abs(dx); int absY = Math.abs(dy); Point preP = p1; splitLine.add(p1); if (absX > absY) { for (int i = 0; i <= absX; i++) { Point newP = new Point(); newP.x = p1.x + Math.round((float) dx * i / (float) absX); newP.y = p1.y + Math.round((float) dy * i / (float) absX); if (preP.y < newP.y) { for (int j = preP.y; j <= newP.y; j++) { Point crossP = new Point(); crossP.x = preP.x; crossP.y = j; splitLine.add(crossP); } } else if (preP.y > newP.y) { for (int j = preP.y; j >= newP.y; j–) { Point crossP = new Point(); crossP.x = preP.x; crossP.y = j; splitLine.add(crossP); } } splitLine.add(newP); preP = newP; } splitLine.add(p2); } else { for (int i = 0; i <= absY; i++) { Point newP = new Point(); newP.x = p1.x + Math.round((float) dx * i / (float) absY); newP.y = p1.y + Math.round((float) dy * i / (float) absY); if (preP.x < newP.x) { for (int j = preP.x; j <= newP.x; j++) { Point crossP = new Point(); crossP.y = preP.y; crossP.x = j; splitLine.add(crossP); } } else if (preP.x > newP.x) { for (int j = preP.x; j >= newP.x; j–) { Point crossP = new Point(); crossP.y = preP.y; crossP.x = j; splitLine.add(crossP); } } splitLine.add(newP); preP = newP; } splitLine.add(p2); } Set<Point> sortSet = new TreeSet<>(new Comparator<Point>() { @Override public int compare(Point o1, Point o2) { //x的升序排列 if (o1.x == o2.x) { return o1.y – o2.y; } else { return o1.x – o2.x; } } }); //去重,并且按排序 Set<Point> set = new HashSet<>(splitLine); sortSet.addAll(set); splitLine= new ArrayList<>(sortSet); return splitLine; }

【文章原创作者:美国服务器 处的文章,转载请说明出处】再发展下来才有了:大霞美的花卉基地和清源山的花博园。

Java算出两个坐标间所有的点,并补齐点保证BFS可

相关文章:

你感兴趣的文章:

标签云: