给定三角形的三个角点和一个点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。
示例代码:
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <stdlib.h>
/* A utility function to calculate area of triangle formed by (x1, y1),
(x2, y2) and (x3, y3) */
float area(int x1, int y1, int x2, int y2, int x3, int y3)
{
return 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) */
bool isInside(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y)
{
/* Calculate area of triangle ABC */
float A = area (x1, y1, x2, y2, x3, y3);
/* Calculate area of triangle PBC */
float A1 = area (x, y, x2, y2, x3, y3);
/* Calculate area of triangle PAC */
float A2 = area (x1, y1, x, y, x3, y3);
/* Calculate area of triangle PAB */
float 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 */
int main()
{
/* 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))
printf ("Inside");
else
printf ("Not Inside");
return 0;
}
输出:
Inside
时间复杂度:O(1)
辅助空间:O(1)