|
15 | 15 | */
|
16 | 16 | public class _221 {
|
17 | 17 |
|
18 |
| - /**The idea is pretty straightforward: use a 2d dp table to store the intermediate results*/ |
19 |
| - public static int maximalSquare(char[][] matrix) { |
20 |
| - if (matrix == null || matrix.length == 0) { |
21 |
| - return 0; |
22 |
| - } |
23 |
| - int m = matrix.length; |
24 |
| - int n = matrix[0].length; |
25 |
| - int max = Integer.MIN_VALUE; |
26 |
| - int[][] dp = new int[m][n]; |
27 |
| - for (int i = 0; i < m; i++) { |
28 |
| - for (int j = 0; j < n; j++) { |
29 |
| - if (i == 0 || j == 0) { |
30 |
| - dp[i][j] = (matrix[i][j] == '1') ? 1 : 0; |
31 |
| - } else { |
32 |
| - if (matrix[i][j] == '0') { |
33 |
| - dp[i][j] = 0; |
| 18 | + public static class Solution1 { |
| 19 | + /** |
| 20 | + * The idea is pretty straightforward: use a 2d dp table to store the intermediate results |
| 21 | + */ |
| 22 | + public int maximalSquare(char[][] matrix) { |
| 23 | + if (matrix == null || matrix.length == 0) { |
| 24 | + return 0; |
| 25 | + } |
| 26 | + int m = matrix.length; |
| 27 | + int n = matrix[0].length; |
| 28 | + int max = Integer.MIN_VALUE; |
| 29 | + int[][] dp = new int[m][n]; |
| 30 | + for (int i = 0; i < m; i++) { |
| 31 | + for (int j = 0; j < n; j++) { |
| 32 | + if (i == 0 || j == 0) { |
| 33 | + dp[i][j] = (matrix[i][j] == '1') ? 1 : 0; |
34 | 34 | } else {
|
35 |
| - dp[i][j] = Math.min(dp[i - 1][j], Math.min(dp[i][j - 1], dp[i - 1][j - 1])) + 1; |
| 35 | + if (matrix[i][j] == '0') { |
| 36 | + dp[i][j] = 0; |
| 37 | + } else { |
| 38 | + dp[i][j] = Math.min(dp[i - 1][j], Math.min(dp[i][j - 1], dp[i - 1][j - 1])) + 1; |
| 39 | + } |
36 | 40 | }
|
| 41 | + max = (max < dp[i][j]) ? dp[i][j] : max; |
37 | 42 | }
|
38 |
| - max = (max < dp[i][j]) ? dp[i][j] : max; |
39 | 43 | }
|
| 44 | + return max * max; |
40 | 45 | }
|
41 |
| - return max * max; |
42 |
| - } |
43 |
| - |
44 |
| - public static void main(String... strings) { |
45 |
| - char[][] matrix = new char[][]{ |
46 |
| - {'1', '0', '1', '0', '0'}, |
47 |
| - {'1', '0', '1', '1', '1'}, |
48 |
| - {'1', '1', '1', '1', '1'}, |
49 |
| - {'1', '0', '0', '1', '0'}, |
50 |
| - }; |
51 |
| - System.out.println(maximalSquare(matrix)); |
52 | 46 | }
|
53 | 47 | }
|
0 commit comments