|
| 1 | +package medium; |
| 2 | + |
| 3 | +public class MaximalSquare { |
| 4 | + |
| 5 | + /**The idea is pretty straightforward: use a 2d dp table to store the intermediate results*/ |
| 6 | + public static int maximalSquare(char[][] matrix) { |
| 7 | + if(matrix == null || matrix.length == 0) return 0; |
| 8 | + int m = matrix.length, n = matrix[0].length; |
| 9 | + int max = Integer.MIN_VALUE; |
| 10 | + int[][] dp = new int[m][n]; |
| 11 | + for(int i = 0; i < m; i++){ |
| 12 | + for(int j = 0; j < n; j++){ |
| 13 | + if(i == 0 || j == 0) dp[i][j] = (matrix[i][j] == '1') ? 1 : 0; |
| 14 | + else { |
| 15 | + if(matrix[i][j] == '0') dp[i][j] = 0; |
| 16 | + else dp[i][j] = Math.min(dp[i-1][j], Math.min(dp[i][j-1], dp[i-1][j-1]))+1; |
| 17 | + } |
| 18 | + max = (max < dp[i][j]) ? dp[i][j] : max; |
| 19 | + } |
| 20 | + } |
| 21 | + return max*max; |
| 22 | + } |
| 23 | + |
| 24 | + public static void main(String...strings){ |
| 25 | + char[][] matrix = new char[][]{ |
| 26 | + {'1', '0', '1', '0', '0'}, |
| 27 | + {'1', '0', '1', '1', '1'}, |
| 28 | + {'1', '1', '1', '1', '1'}, |
| 29 | + {'1', '0', '0', '1', '0'}, |
| 30 | + }; |
| 31 | + System.out.println(maximalSquare(matrix)); |
| 32 | + } |
| 33 | +} |
0 commit comments