So the question itself is quite simple, each input, I am given a width and height, both won’t exceed 200, and then a series of 0 and 1s to represent the 2D plane.
Like this.
4 5
0 0 1 1 1
0 1 1 1 1
1 1 1 1 1
1 1 1 1 1
The goal is to find the area at the right, with an area of 12. Needless to say, rectangles can only be consisted of 1s.
I was thinking about flood-fill while writing this, but it would have to reevaluate for each 1s in the array. What’s the optimal algorithm for this?
The best algorithm I can think of is to traverse the 2D matrix and starting from one corner, top left, to the facing one, bottom right in this case, do the following:
For every 1 you find, find the longest horizontal string of 1s as well as the vertical one. For efficiency, the position to the right has one less 1 than the one to its left (you still have to get its vertical maximum); you just restart the count every time you hit a 0. Same applies when you get to the next line.
The product of the two numbers is the maximum possible area for the rectangle starting at that position. In another data structure, store the position, maxWidth, and maxHeight and make the order based on area with largest area on top. Avoid placing subrectangles for efficiency; you can do this by ignoring a right-adjacent 1 with a maxHeight less than or equal to its own value. I leave the choice of the data structure up to you.
Now you go through the data structure you created and start with the max rectangle. find the nearest 0. You split the rectangle into 2 subrectangles that exclude the horizontal line where the 0 is in and 2 subrectangles that exclude the vertical line where the 0 is in. If the 0 is on the edge, you will get only 3 subrectangles and if it’s in a corner, only 2. Remove the rectangle, insert the newly created subrectangles and maintain the largest area order. Now repeat this process with the next rectangle from the data structure until you find a rectangle with no 0s. That’s the biggest one.
This should be more efficient than checking every possible submatrix.