您的位置:首页 > 其它

Leetcode 221. Maximal Square

2017-07-08 19:11 295 查看
问题描述

Given 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 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0


Return 4.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

问题分析:

题目要求求出全部是1的正方形的面积,要求正方形的面积,只需知道边长即可。

设数组dp[i][j]表示正方形右下角的最大正方形的边长,所以有状态转移方程:

dp[i][j]=min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1]);

代码如下:

public int maximalSquare(char[][] matrix) {
int n=matrix.length;
if(n<=0)
return 0;
int m=matrix[0].length;
int[][]dp=new int
[m];
int result=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
dp[i][j]=matrix[i][j]-'0';
if(i>0&&j>0&&dp[i][j]>0){
dp[i][j]=Math.min(dp[i-1][j-1],Math.min(dp[i-1][j],dp[i][j-1]))+1;
}
if(dp[i][j]>result)
result=dp[i][j];
}
}
return result*result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: