Java 判斷一個點是否在給定矩形內

給出矩形的ABCD四個頂點座標,待判斷點k的座標(x,y)

原理:連接點a與四個頂點,形成四個三角形。如果四個小三角形面積之和等於矩形面積,即說明該點在矩形內部。

三角形面積計算公式:S= \frac{1}{2} \left | (x_{2}-x_{1})(y_{3}-y_{1}) -(x_{3}-x_{1})(y_{2}-y_{1})\right |

代碼:

public class Solution2 {
    public static boolean isInner(int[][] loc, int x, int y) {
        int n = loc.length; //n=4
        double sum = 0;
        for(int i = 0; i < n-1; i++)
            sum += area(loc[i][0],loc[i][1],loc[i+1][0],loc[i+1][1],x,y);
        sum += area(loc[n-1][0],loc[n-1][1],loc[0][0],loc[0][1],x,y);
        double polyArea = 2 * area(loc[0][0],loc[0][1],loc[1][0],loc[1][1],loc[2][0],loc[2][1]);
        if(sum == polyArea) return true;
        else return false;
    }

    //已知座標,求三角形面積
    private static double area(int x1, int y1, int x2, int y2, int x3, int y3) {
        return 0.5 * Math.abs((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1));
    }

    public static void main(String[] args) {
        int[][] loc = {{0,0},{0,10},{20,10},{20,0}};
        int x = 13,y = -7;
        System.out.println(isInner(loc,x,y));
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章