Skip to content

Commit 700ad1d

Browse files
authored
Merge pull request #74 from fattylove/master
Maximal Square
2 parents 39ec006 + e183aa8 commit 700ad1d

File tree

3 files changed

+78
-1
lines changed

3 files changed

+78
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ Input:
312312
Output: 3
313313
```
314314

315-
48. ***【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.
315+
48. [【Maximal Square】](./doc/ms/ms.md) Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
316316

317317
Example:
318318
```

doc/ms/ms.md

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
## Maximal Square
2+
3+
#### 题目
4+
5+
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing
6+
7+
all 1's and return its area.
8+
9+
For example, given the following matrix:
10+
11+
12+
1     0     1     0     0
13+
14+
1     0     1     1      1
15+
16+
1     1      1     1      1
17+
18+
1     0     0     1      0
19+
20+
21+
Return 4.
22+
23+
24+
#### 动态规划:
25+
26+
递推公式:dp[i][j] = min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) + 1
27+
28+
具体代码:
29+
30+
```java
31+
public class MaximalSquare {
32+
33+
public int maximalSquare(char[][] matrix) {
34+
int row = matrix.length;
35+
if (row == 0) {
36+
return 0;
37+
}
38+
int column = matrix[0].length;
39+
int[][] dp = new int[row + 1][column + 1];
40+
int maxSide = 0;
41+
for (int i = 1; i <= row; i++) {
42+
for (int j = 1; j <= column; j++)
43+
if (matrix[i - 1][j - 1] == '1') {
44+
dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;
45+
maxSide = Math.max(dp[i][j], maxSide);
46+
}
47+
}
48+
return maxSide * maxSide;
49+
}
50+
}
51+
52+
```
53+
54+
#### 讲解:
55+
56+
我们用 dp(i, j) 表示以 (i, j) 为右下角,且只包含 1 的正方形的边长最大值。
57+
58+
如果我们能计算出所有 dp(i, j) 的值,那么其中的最大值即为矩阵中只包含 1 的正方形的边长最大值,其平方即为最大正方形的面积。
59+
60+
61+
62+
那么如何计算 dp 中的每个元素值呢?对于每个位置 (i, j),检查在矩阵中该位置的值:
63+
64+
如果该位置的值是 0,则 dp(i, j) = 0,因为当前位置不可能在由 1 组成的正方形中;
65+
如果该位置的值是 1,则 dp(i, j) 的值由其上方、左方和左上方的三个相邻位置的 dp 值决定。具体而言,当前位置的元素值等于三个相邻位置的元素中的最小值加 1 ;
66+
67+
68+
方程如下:
69+
70+
dp(i, j)=min(dp(i−1, j), dp(i−1, j−1), dp(i, j−1))+1
71+
72+
73+
此外,还需要考虑边界条件。如果 i 和 j 中至少有一个为 0,则以位置 (i, j) 为右下角的最大正方形的边长只能是 1,因此 dp(i, j)=1。
74+
75+
76+
77+
![](../../res/ms/1.png)

res/ms/1.png

123 KB
Loading

0 commit comments

Comments
 (0)