最大長方形java

0と1のみを含む2次元のバイナリ行列と、行のサイズx列が与えられた場合、1のみを含む最大の長方形を見つけて、その面積を返します。

例1:

入力:matrix = [["1"、 "0"、 "1"、 "0"、 "0"]、["1"、 "0"、 "1"、 "1"、 "1"]、[ "1"、 "1"、 "1"、 "1"、 "1"]、["1"、 "0"、 "0"、 "1"、 "0"]]
出力:6
説明:最大長方形図1に示すように。
例2:

入力:行列= []
出力:0
例3:

入力:matrix = [["0"]]
出力:0
例4:

入力:matrix = [["1"]]
出力:1
例5:

入力:行列= [["0"、 "0"]]
出力:0

促す:

rows == matrix.length
cols == matrix [0] .length
0 <= row、cols <= 200
matrix [i] [j]是 '0'または '1'

出典:LeetCode
リンク:https ://leetcode-cn.com/problems/maximal-rectangle
著作権はLeetCodeが所有しています商用の再版については、公式の承認に連絡してください。非商用の再版については、出典を示してください。

class Solution {
    
    
    public int maximalRectangle(char[][] matrix) {
    
    
        int m = matrix.length;
        if (m == 0) {
    
    
            return 0;
        }
        int n = matrix[0].length;
        int[][] left = new int[m][n];
        //这题就是在柱状图中的最大矩形(上一篇博客)上暴力求结果

        //获得高
        for (int i = 0; i < m; i++) {
    
    
            for (int j = 0; j < n; j++) {
    
    
                if (matrix[i][j] == '1') {
    
    
                    //最后面有个+1!!!!!!!!!!!!!!!!!
                    left[i][j] = (j == 0 ? 0 : left[i][j - 1]) + 1;
                }
            }
        }
        int ret = 0;
        for (int i = 0; i < m; i++) {
    
    
            for (int j = 0; j < n; j++) {
    
    
                if (matrix[i][j] == '0') {
    
    
                    continue;
                }
                int width = left[i][j];
                int area = width;
                for (int k = i - 1; k >= 0; k--) {
    
    
                    width = Math.min(width, left[k][j]);
                    area = Math.max(area, (i - k + 1) * width);
                }
                ret = Math.max(ret, area);
            }
        }
        return ret;
    }
}

おすすめ

転載: blog.csdn.net/weixin_43824233/article/details/111757454