forked from wey068/Facebook-Interview-Coding
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy path221. Maximal Square.java
More file actions
49 lines (45 loc) · 1.45 KB
/
Copy path221. Maximal Square.java
File metadata and controls
49 lines (45 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
221. Maximal Square
Given a 2D binary matrix filled with 0s and 1s, find the largest square containing only 1s 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.
Solution: DP
dp[i][j] = Math.min(Math.min(dp[i][j-1] , dp[i-1][j-1]), dp[i-1][j]) + 1;
//mine
public int maximalSquare(char[][] matrix) {
if (matrix.length == 0) return 0;
int m = matrix.length, n = matrix[0].length, max = 0;
int[] prev = new int[n + 1];
for (int i = 0; i < m; i++) {
int[] cur = new int[n + 1];
for (int j = 0; j < n; j++)
if (matrix[i][j] == '1') {
cur[j + 1] = Math.min(cur[j], Math.min(prev[j + 1], prev[j])) + 1;
max = Math.max(max, cur[j + 1]);
}
prev = cur;
}
return max * max;
}
// https://leetcode.com/articles/maximal-square/
public int maximalSquare(char[][] matrix) {
if (matrix.length == 0) return 0;
int m = matrix.length, n = matrix[0].length;
int max = 0;
int[] dp = new int[n + 1];
for (int i = 0; i < m; i++) {
int prev = 0;
for (int j = 0; j < n; j++) {
int tmp = dp[j + 1];
if (matrix[i][j] == '1') {
dp[j + 1] = Math.min(dp[j], Math.min(dp[j + 1], prev)) + 1;
max = Math.max(max, dp[j + 1]);
} else dp[j + 1] = 0; // important!!
prev = tmp;
}
}
return max * max;
}