![]() |
VOOZH | about |
Given three corner points of a triangle, and one more point P. Write a function to check whether P lies within the triangle or not.
Example:
Input: A = (0, 0), B = (10, 30), C = (20, 0), P(10, 15)
Output: Inside
Explanation:
B(10,30)
/ \
/ \
/ \
/ P \ P'
/ \
A(0,0) ----------- C(20,0)
Input: A = (0, 0), B = (10, 30), C = (20, 0), P(30, 15)
Output: Outside
Explanation:
B(10,30)
/ \
/ \
/ \
/ \ P
/ \
A(0,0) ----------- C(20,0)
Solution:
Let the coordinates of the three corners be (x1, y1), (x2, y2), and (x3, y3). And coordinates of the given point P be (x, y)
Inside
Time Complexity: O(1)
Auxiliary Space: O(1)
[embed]https://www.youtube.com/watch?v=H9qu9Xptf-w%5B/embed%5D
Exercise: Given coordinates of four corners of a rectangle, and a point P. Write a function to check whether P lies inside the given rectangle or not.
Another Approach - Using Barycentric Coordinate Method: Below is the algorithm to check if a point P lies inside a triangle ABC using the Barycentric Coordinate Method:
Area(ABC) = 0.5 * ||AB x AC||, where ||AB x AC|| is the magnitude of the cross product of vectors AB and AC.
Below is the implementation of the above approach:
Inside
Time Complexity: O(1)
Auxiliary Space: O(1)