题目:
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

解答:
这题思路很重要,一定要理清previous row和current row的参数之间的关系,那么就事半功倍了。left[]表示从左往右到i,出现连续‘1’的string的第一个座标,right[]表示从右往左到i, 出现连续‘1’的string的最后一个座标,height[]表示从上到下的高度。那么用(left[j] - right[j] + 1)(横长) * height[j]就是可能的最大的矩形了。

public int maximalRectangle(char[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }
        int max = 0;
        int m = matrix.length, n = matrix[0].length;
        int[] left = new int[n];
        int[] right = new int[n];
        int[] height = new int[n];
        Arrays.fill(left, 0);
        Arrays.fill(height, 0);
        Arrays.fill(right, n - 1);
        
        for (int i = 0; i < m; i++) {
            int curLeft = 0, curRight = n - 1;
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == '1') height[j]++;
                else height[j] = 0;
            }
            //1 1 0 1
            //1 1 0 1
            //1 1 1 1
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == '1') {
                    //见上述例子,left[j]保证了前面的数组是正方形且没有0的最小矩形,
                    //All the 3 variables left, right, and height can be determined by the information from previous row, and also information from the current row.
                    left[j] = Math.max(left[j], curLeft);
                } else {
                    left[j] = 0;
                    curLeft = j + 1;
                }
            }
            for (int j = n - 1; j >= 0; j--) {
                if (matrix[i][j] == '1') {
                    right[j] = Math.min(right[j], curRight);
                } else {
                    right[j] = n - 1;
                    curRight = j - 1;
                }
            }
            for (int j = 0; j < n; j++) {
                max = Math.max(max, (right[j] - left[j] + 1) * height[j]);
            }
        }
        return max;
    }

guoluona
199 声望14 粉丝