221. 最大正方形

  • 解法一:暴力穷举 时间复杂度 (m*n)^2, 空间复杂度 (1)
public int maximalSquare(char[][] matrix) { 
        int wholeMax = Integer.MIN_VALUE;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (matrix[i][j] == '0') {
                    continue;
                }
                int colSum = Integer.MAX_VALUE;
                int subMax = Integer.MIN_VALUE;
                for (int k = i; k < matrix.length; k++) {
                    int colCount = 0;
                    for (int l = j; l < matrix[0].length; l++) {
                        if (matrix[k][l] == '0') {
                            break;
                        }
                        colCount += 1;
                    }
                    colSum = Math.min(colSum, colCount);
                    subMax = Math.max(subMax, Math.min(colSum, k - i + 1));
                }
                wholeMax = Math.max(wholeMax, subMax);
            }

        }
        return wholeMax * wholeMax;
    }
  • 解法二:dp 递推公式: dp[i][j] = min(dp[i-1][j], dp[i-1][j-1], dp[i][j-1]) + 1, 时间复杂度 (mn), 空间复杂度 (mn)
public int maximalSquare(char[][] matrix) { 
        if (matrix == null || matrix.length == 0) {
            return 0;
        }
        int[][] dp = new int[matrix.length][matrix[0].length];
        int maxLen = 0;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (matrix[i][j] == '0') {
                    continue;
                }
                if (i == 0 || j == 0) {
                    dp[i][j] = 1;
                } else {
                    dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i-1][j-1]), dp[i][j-1]) + 1;
                }
                if (dp[i][j] > maxLen) {
                    maxLen = dp[i][j];
                }
            }
        }
        return maxLen * maxLen;
    }
  • 解法三:dp 递推公式: dp[j] = min(dp[j], dp[j-1], pre_dp[j-1]) + 1, 时间复杂度 (m*n), 空间复杂度 (n)
public int maximalSquare(char[][] matrix) { 
        if (matrix == null || matrix.length == 0) {
            return 0;
        }
        int[] dp = new int[matrix[0].length];
        int maxLen = 0, preJ_1 = 0;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                int temp = dp[j];
                if (matrix[i][j] == '1') {
                    if (i == 0 || j == 0) {
                        dp[j] = 1;
                    } else {
                        dp[j] = Math.min(Math.min(dp[j], dp[j-1]), preJ_1) + 1;
                    }
                    if (dp[j] > maxLen) {
                        maxLen = dp[j];
                    }
                } else {
                    dp[j] = 0;
                }
                preJ_1 = temp;
            }
        }
        return maxLen * maxLen;
    }
posted @ 2019-08-22 07:53  lasclocker  阅读(108)  评论(0编辑  收藏  举报