Finding largest rectangle in 2D array

后端 未结 4 966
别那么骄傲
别那么骄傲 2021-01-12 20:12

I need an algorithm which can parse a 2D array and return the largest continuous rectangle. For reference, look at the image I made demonstrating my question.

4条回答
  •  春和景丽
    2021-01-12 20:48

    Generally you solve these sorts of problems using what are called scan line algorithms. They examine the data one row (or scan line) at a time building up the answer you are looking for, in your case candidate rectangles.

    Here's a rough outline of how it would work.

    Number all the rows in your image from 0..6, I'll work from the bottom up.

    Examining row 0 you have the beginnings of two rectangles (I am assuming you are only interested in the black square). I'll refer to rectangles using (x, y, width, height). The two active rectangles are (1,0,2,1) and (4,0,6,1). You add these to a list of active rectangles. This list is sorted by increasing x coordinate.

    You are now done with scan line 0, so you increment your scan line.

    Examining row 1 you work along the row seeing if you have any of the following:

    • new active rectangles
    • space for existing rectangles to grow
    • obstacles which split existing rectangles
    • obstacles which require you to remove a rectangle from the active list

    As you work along the row you will see that you have a new active rect (0,1,8,1), we can grow one of existing active ones to (1,0,2,2) and we need to remove the active (4,0,6,1) replacing it with two narrower ones. We need to remember this one. It is the largest we have seen to far. It is replaced with two new active ones: (4,0,4,2) and (9,0,1,2)

    So at the send of scan line 1 we have:

    • Active List: (0,1,8,1), (1,0,2,2), (4,0,4,2), (9, 0, 1, 2)
    • Biggest so far: (4,0,6,1)

    You continue in this manner until you run out of scan lines.

    The tricky part is coding up the routine that runs along the scan line updating the active list. If you do it correctly you will consider each pixel only once.

    Hope this helps. It is a little tricky to describe.

提交回复
热议问题