题目描述:
在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。
示例:
输入:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
输出: 4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximal-square
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
emm,看到这个周赛的题目才知道和这个题目相似统计全为1的正方形
class Solution {
public int maximalSquare(char[][] matrix) {
// 考虑将前面的累加,遇见0就停止累加
int result = 0;
if(matrix.length == 0){
return 0;
}
int [][] tem = new int[matrix.length][matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
char[] chars = matrix[i];
for (int j = 0; j < chars.length; j++) {
char aChar = chars[j];
if(aChar == '0'){
tem[i][j] = 0;
}else{
tem[i][j] = 1;
result = 1;
}
}
}
int max = 0;
for (int i = 0; i < tem.length; i++) {
int[] ints = tem[i];
for (int j = 1; j < ints.length; j++) {
if(tem[i][j] == 1){
tem[i][j] += tem[i][j - 1];
int curlen = 1;
int row = i;
int len = tem[i][j];
int min = len;
while (row >= 0 && curlen <= len && result < min){
min = Math.min(tem[row][j],min);
if(min >= curlen && tem[row][j] >= min ){
curlen ++;
row --;
}else{
break;
}
}
result = Math.max(result,curlen - 1);
}
}
}
return (int)Math.pow(result,2);
}
}
评论区有人说可以使用动态规划
官方题解
代码:
public class Solution {
public int maximalSquare(char[][] matrix) {
int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0;
int[][] dp = new int[rows + 1][cols + 1];
int maxsqlen = 0;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
if (matrix[i-1][j-1] == '1'){
dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
maxsqlen = Math.max(maxsqlen, dp[i][j]);
}
}
}
return maxsqlen * maxsqlen;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/maximal-square/solution/zui-da-zheng-fang-xing-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
1万+

被折叠的 条评论
为什么被折叠?



