给定三角形的三个角点和一个点P。编写一个函数来检查P是否位于三角形内。
例子:
输入:A=(0,0),B=(10,30),C=(20,0),P(10,15)
输出:内部
说明:
输入:A=(0,0),B=(10,30),C=(20,0),P(30,15)
输出:外部
说明:
解决方案:
设三个角的坐标为(x1,y1)、(x2,y2)和(x3,y3)。给定点P的坐标为(x,y)
1、计算给定三角形的面积,即上图中三角形ABC的面积。面积A=[x1(y2-y3)+x2(y3-y1)+x3(y1-y2)]/2
2、计算三角形PAB的面积。我们可以用同样的公式。让这个区域为A1。
3、计算三角形PBC的面积。让这个区域为A2。
4、计算三角形PAC的面积。让这个区域为A3。
5、如果P位于三角形内,则A1+A2+A3必须等于A。
示例代码:
/* A utility function to calculate area of triangle formed by (x1, y1),
(x2, y2) and (x3, y3) */
function area(x1, y1, x2, y2, x3, y3)
{
return Math.abs((x1*(y2-y3) + x2*(y3-y1)+ x3*(y1-y2))/2.0);
}
/* A function to check whether point P(x, y) lies inside the triangle formed
by A(x1, y1), B(x2, y2) and C(x3, y3) */
function isInside(x1, y1, x2, y2, x3, y3, x, y)
{
/* Calculate area of triangle ABC */
let A = area (x1, y1, x2, y2, x3, y3);
/* Calculate area of triangle PBC */
let A1 = area (x, y, x2, y2, x3, y3);
/* Calculate area of triangle PAC */
let A2 = area (x1, y1, x, y, x3, y3);
/* Calculate area of triangle PAB */
let A3 = area (x1, y1, x2, y2, x, y);
/* Check if sum of A1, A2 and A3 is same as A */
return (A == A1 + A2 + A3);
}
/* Driver program to test above function */
/* Let us check whether the point P(10, 15) lies inside the triangle
formed by A(0, 0), B(20, 0) and C(10, 30) */
if (isInside(0, 0, 20, 0, 10, 30, 10, 15))
document.write("Inside");
else
document.write("Not Inside");
// This code is contributed by Mayank Tyagi
输出:
Inside
时间复杂度:O(1)
辅助空间:O(1)
练习:给定一个矩形的四个角和一个点P的坐标。编写一个函数来检查P是否位于给定的矩形内。
另一种方法——使用重心坐标法:下面是使用重心坐标方法检查点P是否位于三角形ABC内的算法:
定义一个函数“isInsideTriangle”,它接受四个输入参数:A、B、C和P。
计算点P相对于三角形ABC的重心坐标。为此,我们首先需要计算三角形ABC的面积。我们可以使用叉积来计算三角形ABC的面积,如下所示:
面积(ABC)=0.5*||AB x AC||,其中||AB×AC||是向量AB和AC的叉积的大小。
然后,我们可以计算点P的重心坐标为:
1、a=0.5*|PB x PC ||/面积(ABC)
2、b=0.5*||PC x PA ||/面积(ABC)
3、c=0.5*||PA x PB||/面积(ABC),其中PB、PC和PA分别是从点P到点B、C和A的向量。
如果所有三个重心坐标都是非负的,则点P位于三角形ABC内。返回“内部”。否则,点P位于三角形ABC之外。返回“外部”。
以下是上述方法的示例:
// JavaScript program for the above approach
// Function to check if the point is inside
// the triangle or not
function isInsideTriangle(A, B, C, P) {
// Calculate the barycentric coordinates
// of point P with respect to triangle ABC
let denominator = ((B[1] - C[1]) * (A[0] - C[0]) +
(C[0] - B[0]) * (A[1] - C[1]));
let a = ((B[1] - C[1]) * (P[0] - C[0]) +
(C[0] - B[0]) * (P[1] - C[1])) / denominator;
let b = ((C[1] - A[1]) * (P[0] - C[0]) +
(A[0] - C[0]) * (P[1] - C[1])) / denominator;
let c = 1 - a - b;
// Check if all barycentric coordinates
// are non-negative
if (a >= 0 && b >= 0 && c >= 0) {
return "Inside";
} else {
return "Outside";
}
}
// Driver Code
let A = [0, 0];
let B = [10, 30];
let C = [20, 0];
let P = [10, 15];
// Call the isInsideTriangle function with
// the given inputs
let result = isInsideTriangle(A, B, C, P);
// Print the result
console.log(result);
输出:
Inside
时间复杂度:O(1)
辅助空间:O(1)