Calculate the area of triangle in algorithm question July 16, 2019 Algorithm Math
In algorithm questions, knowing how to calculate the area of the triangle makes problems easy.
Leetcode 1037. Valid Boomerang
Leetcode 812. Largest Triangle Area
Calculate area In an algorithm problem, we usually use (x, y) to represent a point in Cartesian coordinate system. Given three points, how can we calculate the area? we need to know the concept of Vector product firstly.
Vector product
As shown in the figure, the ∣ a × b ∣ |a \times b| ∣ a × b ∣ represents the area of the parallelogram combined with Vector a and Vector b. If we just want to get the area of the triangle, it’s half .
How to calculate vector product?
Formula Given 4 points:
A ( x a , y a ) B ( x b , y b ) C ( x c , y c ) O ( 0 , 0 ) A(x_a,y_a) \ B(x_b, y_b) \ C(x_c,y_c) \ O(0,0) A ( x a , y a ) B ( x b , y b ) C ( x c , y c ) O ( 0 , 0 )
According to vector calculation, we know:
A B ⃗ = A O ⃗ + O B ⃗ = O B ⃗ − O A ⃗ = ( ( x b − x a ) , ( y b − y a ) ) \vec{AB}=\vec{AO} + \vec{OB} = \vec{OB} - \vec{OA} = ((x_b-x_a), (y_b-y_a)) A B = A O + O B = O B − O A = ( ( x b − x a ) , ( y b − y a ) )
A C ⃗ = O C ⃗ − O A ⃗ = ( ( x c − x a ) , ( y c − y a ) ) \vec{AC} = \vec{OC} - \vec{OA} = ((x_c - x_a), (y_c - y_a)) A C = O C − O A = ( ( x c − x a ) , ( y c − y a ) )
so the area of ABC:
Δ A B C = 1 / 2 × ∣ A B ⃗ × A C ⃗ ∣ \Delta_{ABC}=1 / 2 \times | \vec{AB} \times \vec{AC} | Δ A B C = 1 / 2 × ∣ A B × A C ∣
and
A B ⃗ × A C ⃗ = ∣ ( x b − x a ) × ( y c − y a ) − ( y b − y a ) × ( x c − x a ) ∣ = ∣ ( x a × y b + x b × y c + x c × y a ) − ( x c × y b + x b × y a − x a × y c ) ∣ \vec{AB} \times \vec{AC} \\ = |(x_b - x_a) \times (y_c - y_a) - (y_b -y_a) \times (x_c - x_a)| \\ = |(x_a \times y_b + x_b \times y_c + x_c \times y_a) - (x_c \times y_b + x_b \times y_a - x_a \times y_c)| A B × A C = ∣ ( x b − x a ) × ( y c − y a ) − ( y b − y a ) × ( x c − x a ) ∣ = ∣ ( x a × y b + x b × y c + x c × y a ) − ( x c × y b + x b × y a − x a × y c ) ∣
Comments