leetcode 221. Maximal Square & 85. Maximal Rectangle

来源:互联网 发布:王健林天津 知乎 编辑:程序博客网 时间:2024/05/22 08:16
221. Maximal SquareGiven a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.For example, given the following matrix:1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0Return 4.

注意这里的区域是方阵。
对于位置(i,j) 如果其左边,上面,跟左上角都为1,才能算是一个局部的方阵成功。所以dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1])+1。
如果(i,j)为0, dp[i][j]直接为0
这里dp[i][j]记录的其实是方阵的边长。

public class Solution {    public int maximalSquare(char[][] matrix) {        if(matrix==null||matrix.length==0) return 0;        int w = matrix.length;        int h = matrix[0].length;        int[][] dp = new int[w+1][h+1];        int res = 0;        for(int i=1; i<w+1; i++){            for(int j=1; j<h+1;j++){                if(matrix[i-1][j-1] == '1'){                    dp[i][j] = Math.min(dp[i-1][j-1], Math.min(dp[i-1][j], dp[i][j-1])) + 1;                    res = Math.max(dp[i][j], res);                }            }        }        return res*res;    }}

对于不需要是方阵,是矩形即可的情况

85. Maximal RectangleGiven a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.For example, given the following matrix:1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0Return 6.

对于点(i,j),如果为1,记录其左边第一个1,包括自身的位置,记为left[i][j],记录其右边第一个零的位置,记为right[i][j]。这里指的注意的是,left和right还需要根据上一层的left和right来判断。left[i][j] = max(left[i-1][j],left[i][j]),保证矩阵的向上扩展。同理right应该取min。
如果其上边的点不为零,那么矩阵的高度加1,height[j]++,这样包括点(i,j)的矩阵的最大矩阵为height[j] *(right[i][j] - left[i][j])。

public class Solution {    public int maximalRectangle(char[][] matrix) {        if(matrix==null || matrix.length==0) return 0;        int w = matrix.length;        int h = matrix[0].length;        int[] left = new int[h], right = new int[h], height = new int[h];        Arrays.fill(right, h);        int res =0;        for(int i=0; i<w; i++){            int cur_l = 0, cur_r = h;            for(int j=0; j<h;j++){                if(matrix[i][j]=='1'){                    height[j]++;                    left[j] = Math.max(left[j], cur_l);                }else{                    cur_l = j+1;                    height[j] = 0;                    left[j] = 0;                }            }            for(int j = h-1; j>=0; j--){                if(matrix[i][j]=='1'){                    right[j] = Math.min(right[j], cur_r);                }else{                    right[j] = h;                    cur_r = j;                }            }            for(int j = 0; j < h; j++){                res = Math.max(res, (right[j] - left[j])*height[j]);            }        }          return res;    }}
原创粉丝点击