Analysis: This is not an easy problem and the idea is not straightforward.
Since the question requires the area of all ones region, first we can define the region (rectangle) in the matrix. any region in the matrix has several basic properties: 1 corner point, width, and length.
Also which corner point it is decide the exact place of the region, here we consider the bottom-right corner point, because we usually scan the matrix from (0, 0) to right and down direction. for this problem, we also need to consider the all ones requirement, where all the regions are filled with 1 s.
We can then have this data structure:
One 2D array (vector) ones [I] [j], where ones [I] [j] stores the number of contiguous 1 s ended at matrix [I] [j], along ith row. e.g. if matrix [I] = 1011101, then ones [I] =, 1. this array stores the length of the rectangle, for every possible bottom-right corner point.
Having this two values, next is to find the height of the rectangle, as well as keep the all ones requirement.
Start with a corner point [I] [j], since it is the bottom right corner, the rectangle search direction is left and up.
For the left we already have the number of contiguous 1 s ones [I] [j]. How to get the height? We need to scan all the values above ones [I] [j], it is from I-1 to 0. if meets 0, then stop, else compute the possible rectangle area, and store the max. to compute the area, the minimum length of rectangle shocould be compared and stores every time.
Package Level5;/*** Maximal Rectangle *** Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area. **/public class S85 {public static void main (String [] args) {char [] [] matrix = {'0', '1 '}, {'0', '1'}; System. out. println (maximalRectangle (matrix);} public static int maximalRectangle (char [] [] matrix) {int rows = matrix. length; if (rows = 0) {return 0;} int cols = matrix [0]. length; // calculate the width of the entire 1 matrix. int [] [] hOnes = new int [rows] [cols]; // horizontal ones int max = 0; // maximum area for (int I = 0; I
= 0) {minRowWidth = Math. min (minRowWidth, hOnes [minI] [j]); int area = minRowWidth * (I-minI + 1); max = Math. max (max, area); minI -- ;}}} return max ;}}