我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/maximal-square/description/
题目描述:
知识点:动态规划
思路:动态规划
状态定义:
f(x, y) -------- 以(x, y)坐标为右下角的只含1的最大正方形面积
状态转移:
首先,我们很容易对f(x, y)的第一行和第一列进行初始化操作。如果matrix[x][y]是'1',则f(x, y)为1;如果matrix[x][y]是'0',则f(x, y)为0。
(1)如果matrix[x][y]是'0',则f(x, y)为0。
(2)如果matrix[x][y]不是0,
a:f(x - 1, y - 1)为0,显然f(x, y)为1。
b:f(x - 1, y - 1)不为0,显然f(x, y)的值取决于第x行内从(x, y)点开始水平向左找第一个0的位置,假设该位置坐标为(p, y),以及第y列内从(x, y)点开始垂直向上找第一个0的位置,假设该位置坐标为(x, q),则f(x, y)的值取决于j - q和i - p中的较小值。
最后,我们只需返回f(x, y)中的最大值即可。
时间复杂度是O(m * n * max(m, n)),其中m为矩阵的行数,n为矩阵的列数。空间复杂度是O(m * n)。
JAVA代码:
public class Solution {
public int maximalSquare(char[][] matrix) {
int result = 0;
int m = matrix.length;
if(0 == m){
return result;
}
int n = matrix[0].length;
int[][] dp = new int[m][n];
for (int i = 0; i < n; i++) {
if(matrix[0][i] == '1'){
dp[0][i] = 1;
}else{
dp[0][i] = 0;
}
result = Math.max(result, dp[0][i]);
}
for (int i = 1; i < m; i++) {
if(matrix[i][0] == '1'){
dp[i][0] = 1;
}else{
dp[i][0] = 0;
}
result = Math.max(result, dp[i][0]);
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if(matrix[i][j] == '0'){
dp[i][j] = 0;
}else{
int temp = (int) Math.sqrt(dp[i - 1][j - 1]);
if(0 == temp){
dp[i][j] = 1;
}else{
int p = i - 1;
for(; p >= i - temp; p--){
if(matrix[p][j] == '0'){
break;
}
}
int q = j - 1;
for(; q >= j - temp; q--){
if(matrix[i][q] == '0'){
break;
}
}
int min = Math.min(i - p, j - q);
dp[i][j] = (int) Math.pow(min, 2);
}
}
result = Math.max(result, dp[i][j]);
}
}
return result;
}
}
LeetCode解题报告: