![]() |
VOOZH | about |
Your task is to calculate the area of a given polygon.
The polygon consists of n vertices (x1,y1),(x2,y2),.....(xn,yn). The vertices (xi,yi) and (xi+1,yi+1) are adjacent for i=1,2,....,n-1, and the vertices (x1,y1) and (xn,yn) are also adjacent.
Example:
Input: vertices[] = {{1, 1}, {4, 2}, {3, 5}, {1, 4}}
Output: 16Input: vertices[] = {{1, 3}, {5, 6}, {2, 5}, {1, 4}}
Output: 6
Approach:
The idea is to use Shoelace formula calculates the area of a polygon as half of the absolute difference between the sum of products of x-coordinates and y-coordinates of consecutive vertices.
Shoelace formula Formula:
- The formula involves summing the products of the x-coordinates of adjacent vertices and the y-coordinates of the next adjacent vertices, and then subtracting the products of the y-coordinates of adjacent vertices and the x-coordinates of the next adjacent vertices.
- The result is multiplied by 0.5 to get the area of the polygon.
Steps-by-step approach:
Below is the implementation of the above approach:
6
Time complexity: O(N), where N is the number of points.
Auxiliary Space: O(1)