Cho danh sách các đỉnh points = [(x₁,y₁), (x₂,y₂), ...] theo thứ tự (theo chiều kim đồng hồ hoặc ngược) của đa giác đơn giản. Tính diện tích bằng công thức Shoelace (Gia-lăng).
Ví dụ: hình chữ nhật [(0,0), (0,5), (3,5), (3,0)] → diện tích 15.
Công thức Shoelace
Diện tích = |Σ(xᵢ·yᵢ₊₁ - yᵢ·xᵢ₊₁)| / 2, với (xₙ₊₁, yₙ₊₁) = (x₁, y₁).
Ví dụ mã nguồn
def getInfo(x1, y1, x2, y2):
return x1*y2 - y1*x2
def solve(points):
N = len(points)
firstx, firsty = points[0]
prevx, prevy = firstx, firsty
res = 0
for i in range(1, N):
nextx, nexty = points[i]
res += getInfo(prevx, prevy, nextx, nexty)
prevx, prevy = nextx, nexty
res += getInfo(prevx, prevy, firstx, firsty)
return abs(res) / 2.0
points = [(0, 0), (0, 5), (3, 5), (3, 0)]
print(solve(points)) # 15.0
Đầu vào / Đầu ra
Input: [(0, 0), (0,5), (3, 5), (3,0)]
Output: 15.0