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

前端 未结 7 482
忘了有多久
忘了有多久 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:22

    I came here looking for a Python solution. Here is mine, which returns all positions:

    import numpy
    
    s = '''0 0 0 0 1 0 0 0 1 0 0
    0 0 0 0 0 0 1 0 1 0 1
    0 1 0 0 0 0 0 0 0 1 0
    0 0 0 0 0 0 0 0 0 0 0
    0 0 1 1 0 0 0 0 0 0 0
    0 0 0 0 0 1 0 0 0 0 0'''
    
    area = 15
    nrows = 6
    ncols = 11
    skip = 1
    
    a = numpy.fromstring(s, dtype=int, sep=' ').reshape(nrows, ncols)
    w = numpy.zeros(dtype=int, shape=a.shape)
    h = numpy.zeros(dtype=int, shape=a.shape)
    for r in range(nrows):
        for c in range(ncols):
            if a[r][c] == skip:
                continue
            if r == 0:
                h[r][c] = 1
            else:
                h[r][c] = h[r-1][c]+1
            if c == 0:
                w[r][c] = 1
            else:
                w[r][c] = w[r][c-1]+1
            minw = w[r][c]
            for dh in range(h[r][c]):
                minw = min(minw, w[r-dh][c])
                if (dh+1)*minw == area:
                    print(
                        'area', area, 'row', r, 'col', c,
                        'height', dh+1, 'width', minw)
    

    Output:

    area 15 row 4 col 8 height 3 width 5
    area 15 row 5 col 10 height 3 width 5
    

提交回复
热议问题