-3

There is a 2D binary array (2D array of 0 and 1) where m rows and n columns; give an efficient algorithm to find area of largest sub-array (rectangle) consisting entirely of 1s.

public int findMaxRectangleArea(int[][] A,int m,int n);

Can someone please help me with the algorithm part?

Will Vousden
  • 32,488
  • 9
  • 84
  • 95
pooja
  • 9

2 Answers2

2

I'd try an approach like this:

Iterate left to right row by row until you find a 0.

This 0 may already identify two rectangles of 1s:

  • all rows above it
  • from the top left to the position to the left of the 0

One of them is bigger, remember it.

First step

Then recursively descend into the three unknown sectors (two of them partially unknown) that may still contain a rectangle bigger than what you have already found:

Second step

Make sure you don't iterate over the known rows again, that's redundant.

I believe this solution can look at each field at most twice (where a recursion step's sectors overlap), so it should run in θ(x*y).

Kos
  • 70,399
  • 25
  • 169
  • 233
  • not quite there yet... there is a merging step that you omitted that is not trivial. so you've divided the problem after finding a 0, but then after recursively solving the smaller pieces, you need to merge... – thang Feb 06 '13 at 11:06
  • Is the merging step really not trivial? If a solution is in smaller pieces, it's entirely contained in one of them, so the whole solution is just the greatest of the four. If I'm wrong, please show an example. – Kos Feb 06 '13 at 11:24
  • i don't know but it's not listed... trivial or not is subjective. my point is the solution is incomplete. i haven't thought about it... – thang Feb 06 '13 at 11:41
0

It all depends ion how large your smallest array dimension is. If it's smaller than the maximum word size on your target platform, you could make your array into a 1D array of bitmaps and use a series of sliding bitmask windows to find the rectangle.

Simon Elliott
  • 2,087
  • 4
  • 30
  • 39