leetcode221_Maximal_Square

We are looking at a DP problem,
the original question is this:
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

For example, given the following matrix: to find the area of ​​the largest square formed by this rectangle. As shown in the figure, the largest area is obviously when you see this kind of problem, the first feeling is brute force cracking, of course, it will definitely not pass in the end. Since leetcode classifies the problem as a DP problem, it must be Need to write the class state transition equation. Let's analyze it first. There is no doubt that the first row of the rectangle is , because it has only one row. If it is 1, it can only form a square with itself, and the area is 1; then, what about the leftmost column. The reason is as above. . . . . More complicated is how do we analyze it? The idea is that if one , then his state needs to be jointly determined by dp[i - 1][j - 1], dp[i][j - 1], dp[i][j - 1]. Think carefully. isn't it?

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

0 11
4

dp[i][j] = ??
dp[0][i] = matrix[0][i]

dp[j][0] = matrix[j][0],
i > 0 && j > 0

dp[i][j] == '1' 而且 i > 0 j > 0dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;

Then write the code according to this idea to AC. have a good time.

// let's solve the problem using DP
    public static int maximalSquare(char[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return 0;
        }
        int max = Integer.MIN_VALUE;
        int rows = matrix.length;
        int cols = matrix[0].length;
        int[][] dp = new int[rows][cols];

        // topRow
        for (int i = 0; i < cols; i++) {
            dp[0][i] = matrix[0][i] - '0';
            max = Math.max(max, dp[0][i]);
        }
        //leftCol
        for (int j = 0; j < rows; j++) {
            dp[j][0] = matrix[j][0] - '0';
            max = Math.max(max, dp[j][0]);
        }
        // i > 0 && j > 0

        for (int i = 1; i < rows; i++) {
            for (int j = 1; j < cols; 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;
                    max = Math.max(max, dp[i][j]);
                }

            }
        }
        return max*max;


    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326484837&siteId=291194637