您的位置:首页 > 其它

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: