Maximal Rectangle

来源:互联网 发布:手机短信轰炸机软件 编辑:程序博客网 时间:2024/05/17 01:20

题目

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

方法

使用两个矩阵,分别记录每一行连续的1的个数以及每一列连续的1的个数。
    public int maximalRectangle(char[][] matrix) {        int lenX = matrix.length;        if (lenX == 0) {            return 0;        }        int lenY = matrix[0].length;        int[][] maxRec = new int[lenX][lenY];        int[][] height = new int[lenX][lenY];        int[][] length = new int[lenX][lenY];        for (int i = 0; i < lenX; i++) {        for (int j = 0; j < lenY; j++) {        if (matrix[i][j] == '1') {        if (j == 0) {        length[i][j] = 1;        } else {        length[i][j] = length[i][j - 1] + 1;        }                if (i == 0) {        height[i][j] = 1;        } else {        height[i][j] = height[i - 1][j] + 1;        }        } else {        length[i][j] = 0;        height[i][j] = 0;        }        }        }                for (int i = 0; i < lenX; i++) {            for (int j = 0; j < lenY; j++) {            int h = height[i][j];            int l = length[i][j];            int minHeight = h;            int max = 0;            for (int k = 1; k <= l; k++) {            minHeight = Math.min(minHeight, height[i][j + 1 - k]);            max = Math.max(max, k * minHeight);            }            maxRec[i][j] = max;            }        }        int max = 0;        for (int i = 0; i < lenX; i++) {            for (int j = 0; j < lenY; j++) {                if (maxRec[i][j] > max) {                    max = maxRec[i][j];                }            }        }        return max;    }


0 0