# leetCode No.221 Maximal Square

## 题目

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.

## 代码

public class Solution {
public int maximalSquare(char[][] matrix) {
if (matrix.length == 0) {
return 0;
}
int row = matrix.length;
int col = matrix[0].length;
int[][] ret = new int[row][col];
int max = 0;
// 初始化列
for (int i = 0; i < row; i++) {
if (matrix[i][0] == '1') {
ret[i][0] = 1;
max = 1;
}
}
// 初始化行
for (int i = 0; i < col; i++) {
if (matrix[0][i] == '1') {
ret[0][i] = 1;
max = 1;
}
}
//递推公式：f(x,y) = min(f(x-1)(y),f(x)(y-1),f(x-1)(y-1)) + 1
for (int i = 1; i < row; i++) {
for (int j = 1; j < col; j++) {
if (matrix[i][j] == '0') {
ret[i][j] = 0;
}else {
ret[i][j] = Math.min(ret[i - 1][j], Math.min(ret[i][j - 1], ret[i - 1][j - 1])) + 1;
max = Math.max(max, ret[i][j]);
}
}
}
return max * max;
}
}

## 相关链接

#### leetcode 221: Maximal Square

2015-06-05 08:15:01

#### LeetCode221:Maximal Square

2015-06-18 22:53:12

#### LeetCode(221) Maximal Square

2015-08-10 21:53:25

#### LeetCode OJ 之 Maximal Square （最大的正方形）

2015-08-22 10:36:19

#### LeetCode No.221 Maximal Square

2016-11-14 22:01:47

#### [leetcode] 221 Maximal Square(最大全1正方形 &动态规划)

2015-10-04 23:04:17

#### 221. Maximal Square | Java最短代码实现

2016-03-24 10:20:10

#### leetcode_question_85 Maximal Rectangle

2013-09-19 17:29:08

#### 算法学习之动态规划(leetcode 85. Maximal Rectangle）

2017-03-15 16:59:00

#### LeetCode85——Maximal Rectangle

2016-01-28 20:44:55