凸包边上的点求法

下边的代码仅仅是凸包求法的一个简单模拟,并没有经过严格的测试,并且我们假设没有任意两个点在一条直线上,且点的个数大于等于3,

package coursera.week2.sort;

public class Point2D {

    private  double x;

    public void setX(double x){
        this.x = x;
    }
    public double getX() {
        return x;
    }

    private  double y;

    public void setY(double y){
        this.y = y;
    }

    public double getY() {
        return y;
    }

    public Point2D(double x,double y){
        this.x = x;
        this.y = y;
    }

    public static int ccw(Point2D a, Point2D b, Point2D c){
        double ans = (b.x-a.x)*(c.y-a.y) - (b.y-a.y)*(c.x-a.x);
        if(ans > 0){ //ccw counter-clockwise
            return 1;
        }
        else if(ans < 0){ //clockwise
            return -1;
        }
        else{ //colinear
            return 0;
        }
    }

}


package coursera.week2.sort;

import java.awt.print.Printable;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Stack;

import sun.net.www.content.audio.x_aiff;

import com.sun.org.apache.xml.internal.security.Init;

public class Graham {

    Stack<Point2D> hull = new Stack<Point2D>();
    private Point2D[] p;
    private Point2D pYMin;

    public Graham(Point2D[] p){
        this.p = p;
        init();
    }
    public void init(){
        Arrays.sort(p, new Point2D_Y());//now p[0].y  is the smallest.
        pYMin = p[0]; //save the point with min y
        Arrays.sort(p, new Polar()); //sort the p with polar ascending
    }

    public void scanner(){
        hull.push(p[0]);
        hull.push(p[1]);
        int n = p.length;
        for(int i = 2; i<n; i++){
            Point2D top = hull.pop();
            while(Point2D.ccw(hull.peek(), top, p[i])<=0){
                hull.pop();
            }
            hull.push(top);
            hull.push(p[i]);
        }
    }

    class Point2D_Y implements Comparator<Point2D>{

        @Override
        public int compare(Point2D p, Point2D q) {
            //注意,此方法实现从小到大排序
            if(p.getY() >= q.getY()) return 1;
            return -1;
        }
    }

    class Polar implements Comparator<Point2D> {

        @Override
        public int compare(Point2D p, Point2D q) {
            if(polar(p) >= polar(q)){
                return 1;
            }
            return -1;
        }

    }

    private double polar(Point2D p){
        Double x = p.getX()-pYMin.getX();
        Double y = p.getY()-pYMin.getY();
        if(x==0)
            return -10;
        return Math.atan2(y,x);
    }

    public void print(){
        while(!hull.empty()){
            Point2D p = hull.pop();
            System.out.println(p.getX()+""+p.getY());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值