在一個由 0 和 1 組成的二維矩陣內,找到只包含 1 的最大正方形,並返回其面積。
示例:
輸入:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
輸出: 4
題解關鍵思路:
這道題檢查正方形的第四個角作遞歸
dp記錄最大正方形的邊長
代碼:
class Solution {
public int maximalSquare(char[][] matrix) {
//只能總結經驗嗎??!!
if ( matrix.length <= 0 || matrix[0].length <= 0 ) {
return 0;
}
int row = matrix.length;
int col = matrix[0].length;
int dp[][] = new int[row+1][col+1];
int max = 0;
for( int i = 1 ; i <= row ; i++ ) {
for( int j = 1 ; j <= col ; j++ ) {
if ( matrix[i-1][j-1] == '1' ) {
dp[i][j] = Math.min( Math.min(dp[i-1][j] , dp[i][j-1]) , dp[i-1][j-1] ) + 1;
}
max = Math.max( max , dp[i][j] );
}
}
return max * max;
}
}