1. 程式人生 > 實用技巧 >力扣-221-最大正方形

力扣-221-最大正方形

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 = new
int[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); } }