給出矩形的ABCD四個頂點座標,待判斷點k的座標(x,y)
原理:連接點a與四個頂點,形成四個三角形。如果四個小三角形面積之和等於矩形面積,即說明該點在矩形內部。
三角形面積計算公式:
代碼:
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));
}
}