力扣-221-最大正方形
阿新 • • 發佈:2020-09-23
package LeetCode; public class LeetCode221_2 { public static int maximalSquare(char[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0; int n = matrix.length, m = matrix[0].length; int ans = -1; int[][] dp = newint[n][m]; for(int i = 0; i < n; i++) { if(matrix[i][0] == '1') dp[i][0] = 1; } for(int j = 0; j < m; j++) { if(matrix[0][j] == '1') dp[0][j] = 1; } for(int i = 1; i < n; i++) { for(int j = 1; j < m; j++) {if(matrix[i][j] == '1') dp[i][j] = Math.min(dp[i-1][j-1], Math.min(dp[i][j-1], dp[i-1][j])) + 1; } } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { ans = Math.max(ans, dp[i][j]); } }return ans * ans; } public static void main(String[] args) { char[][] matrix = {{'1','0','1','0','0'}, {'1','0','1','1','1'}, {'1','1','1','1','1'}, {'1','0','0','1','0'}}; int res = maximalSquare(matrix); System.out.println(res); } }