Search matrix for all rectangles of given dimensions (select blocks of seats)

前端 未结 7 442
忘了有多久
忘了有多久 2020-12-08 11:46

All,

I have been trying to work out how to select say 15 tickets within a single block of seats.

EDIT: the problem is - how to find all rect

相关标签:
7条回答
  • 2020-12-08 12:23

    This problem is much better solved outside mysql, in another language. In other words, you have a matrix of seats, some of which are occupied (grey ones):

    enter image description here

    and you want to find all rectangles of given dimensions, say 3x5. You can do this very efficiently by two pass linear O(n) time algorithm (n being number of seats):

    1) in a first pass, go by columns, from bottom to top, and for each seat, denote the number of consecutive seats available up to this one:

    enter image description here

    repeat, until:

    enter image description here

    2) in a second pass, go by rows, and look for at least 5 consecutive numbers greater or equal to 3:

    enter image description here

    so, finally, you get:

    enter image description here

    which yields the solution: these number sequences (green areas) are top edges of the 2 possible rectangles 3x5 of free seats.

    The algorithm could be easily enhanced to e.g. get all rectangles with maximum area. Or, it could be used to find any continuous regions (not only rectangle-shaped) of N seats - just, during the second pass, look for continuous sequence of numbers which sums up to at least N.

    0 讨论(0)
提交回复
热议问题