221. Maximal Square

65次阅读

共计 928 个字符,预计需要花费 3 分钟才能阅读完成。

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
难度:medium
题目:给定由 0,1 组成的矩阵,找出由 1 组成的最大方块并返回其面积。
思路:动态规划转换方程 grid[i][j] = Math.min(grid[i][j – 1], grid[i – 1][j], grid[i – 1][j – 1]) + 1 (matrix[i][j] = ‘1’)
Runtime: 7 ms, faster than 97.80% of Java online submissions for Maximal Square.Memory Usage: 40.8 MB, less than 70.46% of Java online submissions for Maximal Square.
class Solution {
public int maximalSquare(char[][] matrix) {
if (null == matrix || matrix.length < 1) {
return 0;
}
int maxSquare = 0, m = matrix.length, n = matrix[0].length;
int[][] grid = new int[m][n];
for (int i = 0; i < m; i++) {
if (‘1’ == matrix[i][0]) {
grid[i][0] = 1;
maxSquare = 1;
}
}
for (int i = 0; i < n; i++) {
if (‘1’ == matrix[0][i]) {
grid[0][i] = 1;
maxSquare = 1;
}
}

for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (‘1’ == matrix[i][j]) {
grid[i][j] = Math.min(grid[i – 1][j – 1],
Math.min(grid[i – 1][j], grid[i][j – 1])) + 1;
maxSquare = Math.max(maxSquare, grid[i][j]);
}
}
}

return maxSquare * maxSquare;
}
}

正文完
 0