Finding rectangles in a 2d block grid

前端 未结 4 995
孤街浪徒
孤街浪徒 2020-12-03 07:54

Let\'s say I have a grid of blocks, 7x12. We use the colors \'*\',\'%\',\'@\' and an empty cell \'-\'.

1 2 3 4 5 6 7
- - - - - - -  1
- - - - - - -  2
% % -          


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 08:41

    My own solution is to find the biggest rectangle, using the same algorithm as in @j_random_hacker answer, then split the remaining area into 4 regions, and recursively search for the biggest rectangle again in each of these regions.

    Link to C++ sources

    It will find less rectangles than the accepted answer, because I have found it difficult to adopt that algorithm to save each intermediary rectangle when searching for the biggest one. The algorithm skips all smaller rectangles, so we have to iterate through every point in our grid, to save every rectangle possible, then discard smaller ones, and this bumps the algorithm back to O(M³ ⋅ N³) complexity.

    We can split the remaining area in two ways, the algorithm will check both, and will use the option which covers the most area, so it will perform the recursive call twice - first time to calculate the area, second time to fill the output array.

        ****|***|***                ************
        ****|***|***                ************
        ****#####***                ----#####---
        ****#####***        vs      ****#####***
        ****#####***                ----#####---
        ****|***|***                ************
    

    We can leave only one choice of area split to make the algorithm run faster, because this area comparison does not provide much improvement to the amount of detected rectangles, to be honest.

    Edit: I just realized that recursively checking both splitting variants raises the algorithm to factorial complexity, to something like O(min(M,N)!). So I've disabled the second area split, which leaves the algorithm with complexity around O(M⋅N⋅log(M⋅N)).

提交回复
热议问题