Leetcode:Maximal Square & Maximal Rectangle
2017-10-05 16:53
218 查看
url : https://leetcode.com/problems/maximal-square/description/
url : https://leetcode.com/problems/maximal-rectangle/description/
解题思路:
Maximal Square 此题相对简单,使用动态规划。matrix[i,j]==0时, dp[i,j]=0;
matrix[i,j]==1 时,dp[i,j]=min(dp[i-1,j-1],dp[i-1,j],dp[i,j-1])+1
代码示例
public int maximalSquare(char[][] matrix) { int row = matrix.length; int width = matrix[0].length; if(row == 0) return 0; int []dp = new int[width+1]; int pre = 0, temp = 0; int max = Integer.MIN_VALUE; for(int i=0;i<row;i++){ pre = 0; for(int j=0;j<width;j++){ if(matrix[i][j]=='0'){ temp = 0; dp[j] = pre; pre = temp; }else{ temp = Math.min(pre,dp[j]); temp = Math.min(temp,dp[j+1]); dp[j] = pre; pre = temp+1; max = Math.max(max,pre); } } dp[width] = pre; } return max*max; }
Maximal Rectangle 相对复杂一些,需要对动态规划进行一些变化。
left[i,j] 表示从matrix[i,j]位置向左连续为”1”的最左边的位置和left[i-1,j] 的最大值;
right[i,j]表示从matrix[i,j]位置向右连续为”1”的最右边的位置和right[i-1,j]的最小值;
hight[i,j]表示从matrix[i,j]向上连续的“1”的个数;
最后的面积为: max{(right[i,j]-left[i,j])*height[i,j]}
下面给出代码:
public int maximalRectangle(char[][] matrix) { int row = matrix.length; if(row == 0) return 0; int width = matrix[0].length; int[]left = new int[width]; int[]right = new int[width]; int[]height = new int[width]; int result = 0; for(int i=0;i<width;i++) right[i]=width; for(int i=0;i<row;i++){ int curLeft = 0, curRight = width; for(int j = 0; j < width; j++){ if(matrix[i][j]=='1'){ height[j]++; }else{ height[j] = 0; } } for(int j=0;j<width;j++){ if(matrix[i][j]=='1'){ left[j] = Math.max(curLeft,left[j]); }else{ left[j] = 0; curLeft = j+1; } } for(int j=width-1;j>=0;j--){ if(matrix[i][j]=='1'){ right[j] = Math.min(curRight,right[j]); }else{ right[j] = width; curRight = j; } } for(int j=0;j<width;j++){ result = Math.max(result, (right[j]-left[j])*height[j]); } } return result; }
相关文章推荐
- 【LeetCode】Maximal Rectangle && Maximal Square
- leetcode085_221:Maximal Rectangle&Maximal Square
- LeetCode之“动态规划”:Maximal Square && Largest Rectangle in Histogram && Maximal Rectangle
- leetcode -- Maximal Square -- DP重点
- leetcode----DP----Maximal Square
- Maximal Square -- leetcode
- LeetCode || Maximal Square
- leetCode(27):Maximal Square 分类: leetCode 2015-07-02 09:05 152人阅读 评论(0) 收藏
- LeetCode Maximal Square
- Leetcode Maximal Square
- leetCode(27):Maximal Square
- leetcode每日解题思路 221 Maximal Square
- leetCode_Maximal Square
- Leetcode Maximal Square
- [LeetCode][JavaScript]Maximal Square
- LeetCode: 221_Maximal Square | 二维0-1矩阵中计算包含1的最大正方形的面积 | Medium
- [leetcode] Maximal Square
- Maximal Square || LeetCode
- Leetcode Maximal Square
- LeetCode(221) Maximal Square