【动态规划】leetcode221最大正方形(Java)

【动态规划】leetcode221 最大正方形

题目详情

【动态规划】leetcode221最大正方形(Java)_第1张图片

代码实现【1】

dp[i][j] 表示maxtrix[i][j]所在行连续1的数量

public class Solution {
    public int maximalSquare(char[][] matrix){
        if(matrix.length == 0)
            return 0;
        if(matrix.length == 1) {
            for (int j = 0; j < matrix[0].length; j++)
                if (matrix[0][j] == '1')
                    return 1;
            return 0;
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int[][] dp = new int[row][col];

        int maxArea = 0;
        // 初始化第一列dp
        for(int i = 0; i < row; i ++){
            if(matrix[i][0] == '1')
                dp[i][0] = 1;
        }

        for(int i = 0; i < row; i ++){
            for(int j = 1; j < col; j ++){
                if(matrix[i][j] == '1'){
                    dp[i][j] = dp[i][j - 1] + 1;
                    int width = dp[i][j];
                    for(int k = 0; k <= i; k ++){
                        if(dp[i - k][j] == 0) {
                            maxArea = Math.max(maxArea, 1);
                            break;
                        }else{
                            width = Math.min(width, dp[i - k][j]);
                            int len = Math.min(k + 1, width);
                            maxArea = Math.max(maxArea, len * len);
                        }
                    }
                }else{
                    dp[i][j] = 0;
                }
            }
        }
        return maxArea;
    }
}

代码实现【2】

/***
 * 动态规划 dp[][] 表示能组成正方形最大边长
 * dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) + 1
 */

public class Solution2 {
    public int maximalSquare(char[][] matrix){
        if(matrix.length == 0)
            return 0;
        if(matrix.length == 1) {
            for (int j = 0; j < matrix[0].length; j++)
                if (matrix[0][j] == '1')
                    return 1;
            return 0;
        }
        int rows = matrix.length;
        int cols = matrix[0].length;
        int[][] dp = new int[rows + 1][cols + 1];
        int maxLen = 0; //最大边长
        for(int i = 1; i < dp.length; i ++){
            for(int j = 1; j < dp[0].length; j ++){
                if(matrix[i - 1][j - 1] == '1'){
                    dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;
                    maxLen = Math.max(maxLen, dp[i][j]);
                }
            }
        }
        return maxLen * maxLen;
    }
}

你可能感兴趣的:(Java,leetcode,算法,leetcode,动态规划,数据结构,java)