凸包分治法 java_分治法在求解凸包问题中的应用(JAVA)--快包算法

本文介绍了一种使用Java实现的凸包分治算法,通过示例代码展示了如何处理二维平面上的点集,找出包含所有点的最小凸包。文章涉及了点的比较、排序以及递归的分治过程,利用交叉乘积判断点相对于直线的位置,最终得到凸包上的关键点。
摘要由CSDN通过智能技术生成

import java.util.Arrays;

import java.util.Comparator;

import java.util.Scanner;

class Point {

double x;

double y;

public Point(double x, double y) {

this.x = x;

this.y = y;

}

}

public class Main {

static Point[] point;

static double[] s = new double[6];

static Scanner in = new Scanner(System.in);

public static void main(String[] args) {

int n = in.nextInt();

point = new Point[n];

// for (int i = 0; i < n; i++) {

// int a = in.nextInt();

// int b = in.nextInt();

// point[i] = new Point(a, b);

// }

point[0] = new Point(1,3);

point[1] = new Point(2,1);

point[2] = new Point(3,5);

point[3] = new Point(4,4);

point[4] = new Point(5,2);

point[5] = new Point(3,2);

Arrays.sort(point,0, n, new Comparator() {

@Override

public int compare(Point o1, Point o2) {

if (o1.x - o2.x == 0) {

return (int) (o1.y - o2.y);

}

return (int) (o1.x - o2.x);

}

});

System.out.println(point[0].x + "," + point[0].y);

hull(1, n-1,point[0],point[0]);

}

private static void hull(int l,int r,Point p1,Point p2){

int x=l;

int i=l-1,j=r+1;

/**

* 找出距离直线p1-p2最远的点p3

* */

for (int k = l; k <= r; k++){

if (s[x] - s[k] <= 0) {

x=k;

}

}

Point p3 = point[x];

/**

* p1-p3左侧的点

* */

for (int k = l; k <= r; k++) {

s[++i] = cross(point[k], p1, p3);

if (s[i] > 0) {

Point temp = point[i];

point[i] = point[k];

point[k] = temp;

} else {

i--;

}

}

/**

* 直线p3-p2右侧的点

* */

for (int k=r;k>=l;k--) {

s[--j]=cross(point[k], p3, p2);

if (s[j] > 0) {

Point temp = point[j];

point[j] = point[k];

point[k] = temp;

} else {

j++;

}

}

/**

* 分治,并中序输出

* */

if (l <= i) {

hull(l, i, p1, p3);

}

System.out.println(p3.x + "," + p3.y);

if (j <= r) {

hull(j, r, p3, p2);

}

}

private static double cross (Point a, Point b, Point c) {

return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值