php 检查给定点是否位于三角形内(Check whether a given point lies inside a triangle or not)

给定三角形的三个角点和一个点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。 

示例代码: 

<?php
 
/* 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 abs(($x1 * ($y2 - $y3) + 
                $x2 * ($y3 - $y1) +  
                $x3 * ($y1 - $y2)) / 2.0);
}
 
/* A function to check whether 
   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 */
    $A = area ($x1, $y1, $x2, $y2, $x3, $y3);
     
    /* Calculate area of triangle PBC */
    $A1 = area ($x, $y, $x2, $y2, $x3, $y3);
     
    /* Calculate area of triangle PAC */
    $A2 = area ($x1, $y1, $x, $y, $x3, $y3);
     
    /* Calculate area of triangle PAB */
    $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 Code
    /* Let us check whether the 
       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))
        
        echo "Inside";
    
    else
        
        echo "Not Inside";
 
 
// This code is contributed by anuj_67.
?> 

输出:
    Inside

时间复杂度:O(1)

辅助空间:O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csdn_aspnet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值