Leetcode - Maximum Square

本文介绍了一种算法,用于寻找二维二进制矩阵中最大的全由1构成的正方形,并返回该正方形的面积。提供了两种方法:一种是基于动态规划的方法,另一种是对最大矩形算法的扩展。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 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.

[分析]
思路1:修改MaxRectangle的实现,求解每一行上最大矩形面积改为求解最大正方形面积。
思路2:dp[i][j]表示以(i, j)为右下角顶点的正方形的边长,则(i, j)处为1时dp[i][j] = min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]) + 1


public class Solution {
// Method 2: http://blog.youkuaiyun.com/xudli/article/details/46371673
public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return 0;
int rows = matrix.length, cols = matrix[0].length;
int max = 0;
int[][] dp = new int[rows][cols];
for (int i = 0; i < rows; i++) {
dp[i][0] = matrix[i][0] == '1' ? 1 : 0;
max = Math.max(max, dp[i][0]);
}
for (int j = 0; j < cols; j++) {
dp[0][j] = matrix[0][j] == '1' ? 1 : 0;
max = Math.max(max, dp[0][j]);
}
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (matrix[i][j] == '1') {
dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;
max = Math.max(max, dp[i][j]);
}
}
}
return max * max;
}
// Method 1: extension of maximalRectangle
public int maximalSquare1(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return 0;
int rows = matrix.length, cols = matrix[0].length;
int[] h = new int[cols + 1];
int max = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == '1')
h[j] += 1;
else
h[j] = 0;
}
max = Math.max(max, getMaxSquare(h));
}
return max;
}
public int getMaxSquare(int[] h) {
LinkedList<Integer> stack = new LinkedList<Integer>();
int max = 0;
for (int i = 0; i < h.length; i++) {
while (!stack.isEmpty() && h[i] < h[stack.peek()]) {
int currH = h[stack.pop()];
while (!stack.isEmpty() && h[stack.peek()] == currH)
stack.pop();
int len = Math.min(i - (stack.isEmpty() ? -1 : stack.peek()) - 1, currH);

max = Math.max(max, len * len);
}
stack.push(i);
}
return max;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值