题目描述:
在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。
示例:
输入:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
输出: 4
分析:
- 问题拆解:
以某个位置为例,判断以该位置为右下角的正方形需要判断三个方向,左、上、左上
- 状态定义:
以当前点为右下角的正方形的边长的最大值
- 递推方程:
这个递推方程不太好想到,但是特别容易理解:
代码实现:
Java
/*
* @lc app=leetcode.cn id=221 lang=java
*
* [221] 最大正方形
*/
// @lc code=start
class Solution {
public int maximalSquare(char[][] matrix) {
if(matrix.length == 0 || matrix[0].length == 0){
return 0;
}
int m = matrix.length;
int n = matrix[0].length;
int [][] map = new int[m][n];
int result = 0;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(matrix[i][j] == '1'){
if(i == 0 | j == 0){
map[i][j] = matrix[i][j] == '1' ? 1 : 0;
}else{
map[i][j] = Math.min(map[i - 1][j], Math.min(map[i][j - 1], map[i - 1][j - 1])) + 1;
}
result = Math.max(result, map[i][j]);
}
}
}
return result * result;
}
}
// @lc code=end
Python
待补充