Given four points of a rectangle, and one more point P. Write a function to check whether P lies within the given rectangle or not.
Input : R = [(10, 10), (10, -10), (-10, -10), (-10, 10)] P = (0, 0) Output : yes Illustration :
Input : R = [(10, 10), (10, -10), (-10, -10), (-10, 10)], P = (20, 20) Output : no Illustration :
Prerequisite: Check whether a given point lies inside a triangle or not
Approach : Let the coordinates of four corners be A(x1, y1), B(x2, y2), C(x3, y3) and D(x4, y4). And coordinates of the given point P be (x, y)
1) Calculate area of the given rectangle, i.e., area of the rectangle ABCD as area of triangle ABC + area of triangle ACD.
Area A = [ x1(y2 – y3) + x2(y3 – y1) + x3(y1-y2)]/2 + [ x1(y4 – y3) + x4(y3 – y1) + x3(y1-y4)]/2
2) Calculate area of the triangle PAB as A1.
3) Calculate area of the triangle PBC as A2.
4) Calculate area of the triangle PCD as A3.
5) Calculate area of the triangle PAD as A4.
6) If P lies inside the triangle, then A1 + A2 + A3 + A4 must be equal to A.
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.