Find sum of elements within the area of 45 degree rotated rectangle

Viewed 190
  • Given a matrix of integers, we'd like to consider the sum of the elements within the area of a 45° rotated rectangle.

  • More formally, the area is bounded by two diagonals parallel to the main diagonal and two diagonals parallel to the secondary diagonal.

  • The dimensions of the rotated rectangle are defined by the number of elements along the borders of the rectangle. Given integers a and b representing the dimensions of the rotated rectangle, and matrix (a matrix of integers), your task is to find the greatest sum of integers contained within an a x b rotated rectangle.

    Note: The order of the dimensions is not important - consider all a x b and b x a rectangles.
    
    matrix = [[1, 2, 3, 4, 0],
              [5, 6, 7, 8, 1],
              [3, 2, 4, 1, 4],
              [4, 3, 5, 1, 6]] 
    
    a = 2, and b = 3, the output should be rotatedRectSum(matrix, a, b) = 36.

I need help to understand the below solution.

Kindly help understand below points

  • What is cols spread and rows spread here?

  • range(w_-1, len(matr[0])-(h_-1))

  • range(len(matr)-(w_+h_-1)+1)

  • perimetr(matr, i+k, j+max(k-1,0), w_-k, h_-k)

    def perimetr(matr, i, j, w, h):
      s = matr[i][j]
      dd = [(h, 1, 1)] if w == 1 else [(w, 1, -1)] if h == 1 else [(w, 1, -1), (h, 1, 1), (w, -1, 1), (h-1, -1, -1)]
      for n, x, y in dd:
        if n <= 1: break
        c = 1
        while c < n:
          i += x
          j += y
          c += 1
          s += matr[i][j]
      return s
    
    def rectangles(matr, w, h):
      mm = 0
      for w_, h_ in [(w, h), (h, w)]:
        for j in range(w_-1, len(matr[0])-(h_-1)): # rectangle cols spread [j-(w-1), j+(h-1)]
          for i in range(len(matr)-(w_+h_-1)+1): # each rectangle spreads w+h-1 rows
            # square at (i,j) is sum of all perimeters of inner rectangles
            mm = max(mm, sum([perimetr(matr, i+k, j+max(k-1,0), w_-k, h_-k) for k in range(min(w_, h_))])) 
      return mm
0 Answers
Related