Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example:
Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4
解释下题目:
给定一个数组,找出其中最大的正方形面积。
1. 动态规划
实际耗时:5ms
public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int sideLength = 0;
int[][] dp = new int[matrix.length + 1][matrix[0].length + 1];
//init
for (int i = 0; i < matrix.length; i++) {
dp[i][0] = 0;
}
for (int i = 0; i < matrix[0].length; i++) {
dp[0][i] = 0;
}
//dynamic
for (int i = 1; i <= matrix.length; i++) {
for (int j = 1; j <= matrix[0].length; j++) {
if (matrix[i - 1][j - 1] == '1') {
int left = dp[i][j - 1];
int up = dp[i - 1][j];
int leftUp = dp[i - 1][j - 1];
dp[i][j] = Math.min(left, Math.min(up, leftUp)) + 1;
sideLength = Math.max(sideLength, dp[i][j]);
} else {
dp[i][j] = 0;
}
}
}
return (int) Math.pow(sideLength, 2);
}
其实做这种题目肯定是动态规划,首先开辟一个额外的数组,然后假设你已经实现了相关的功能,在上面题目中就是假设我已经实现了一个dp,这个dp记录的是以目前这个位置为右下角的正方形的面积,而且每一个都能根据它的左上方、左边、上面的三个来进行推测,然后动态规划就完成了。