-
Notifications
You must be signed in to change notification settings - Fork 0
221. Maximal Square
Jacky Zhang edited this page Sep 12, 2016
·
1 revision
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 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.
解题思路为Dynamic Programming。
令dp[i][j]表示以matrix[i+1][j+1]为右下角的max square的边长。 左,上,和左上三个格子决定了square的大小,当前格子若是1的话,这个格子max square的边长为以上三者的最小值+1。
public class Solution {
public int maximalSquare(char[][] matrix) {
if(matrix == null || matrix.length == 0) return 0;
int m = matrix.length, n = matrix[0].length, res = 0;
int[][] dp = new int [m+1][n+1];
for(int i = 1; i <= m; i++) {
for(int j = 1; j <= n; j++) {
if(matrix[i-1][j-1] == '1') {
dp[i][j] = Math.min(Math.min(dp[i-1][j-1], dp[i][j-1]), dp[i-1][j]) + 1;
res = Math.max(res, dp[i][j]);
}
}
}
return res * res;
}
}