Find minimum area of rectangle with given set of coordinates in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of some points in XY plane. We have to find the minimum area of rectangle that can be formed from these points. The side of the rectangle should be parallel to the X and Y axes. If we cannot form the rectangle, then return 0. So if the array of points is like [(1, 1), (1, 3), (3, 1), (3, 3), (2, 2)]. The output will be 4. As the rectangle can be formed using the points (1, 1), (1, 3), (3, 1) and (3, 3).

To solve this, give the points by x coordinates, so that points on straight vertical lines are grouped together. Then for each pair of points in the group like (x, y1) and (x, y2) we will find the smallest rectangle with this pair of points, as the right most edge of the rectangle to be formed. We can do this by keeping track of all other pairs of points, we have visited before. Finally return the minimum possible area of the rectangle obtained.

Example

import collections
def findMinArea(Arr):
   columns = collections.defaultdict(list)
   for x, y in Arr:
      columns[x].append(y)
   lastx = {}
   ans = float('inf')
   for x in sorted(columns):
      col = columns[x]
      col.sort()
      for j, y2 in enumerate(col):
         for i in range(j):
            y1 = col[i]
   if (y1, y2) in lastx:
      ans = min(ans, (x - lastx[y1, y2]) * (y2 - y1))
      lastx[y1, y2] = x
   if ans < float('inf'):
      return ans
   else:
      return 0
A = [[1, 1], [1, 3], [3, 1], [3, 3], [2, 2]]
print('Minimum area of rectangle:',findMinArea(A))

Output

Minimum area of rectangle: 4
raja
Published on 18-Dec-2019 14:55:05
Advertisements