LeetCode 221. Maximal Square

Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.

idea:
since we know that this problem is solved in DP,
now let’s try to do that in DP.
dp[i][j] represents for the length of edge of this square that in the [0,0] from [i, j]. there will be a global maximum maintained in the whole process
i tried to implement that, but the first time i try, the code is wrong;

class Solution {
    public int maximalSquare(char[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return 0;
        }
        int m = matrix.length;
        int n = matrix[0].length;
        int[][] dp = new int[m+1][n+1];
        int max = 0;
        
        for (int i = 1; i<= m; i++) {
            for (int j = 1; j<= n; j++) {
                if (matrix[i-1][j - 1] == '0') {
                    dp[i][j] = 0;
                } else {
                    dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + 1;
                    max = Math.max(max, dp[i][j]);
                    
                }
                System.out.println(dp[i][j]);
            }
        }
        return max * max;
    }
}

but the problem is very trivia, think about the
0 1
1 1
situation, the right bottom will be 2 but not,

and the following code is right, but donlt actually understand it.

class Solution {
    public int maximalSquare(char[][] matrix) {
        if(matrix == null || matrix.length == 0) return 0;
        
        int[] dp = new int[matrix[0].length + 1];//dp[i] represnets for ending in current position, the longest 1 from previous 
        
        int maxEdge = 0;
        int prev = 0;
        
        for(int i = 1; i<= matrix.length; i++) {
            for(int j = 1; j<= matrix[0].length; j++) {
                int temp = dp[j]; //copy
                if(matrix[i-1][j-1] == '1') {
                    dp[j] = Math.min(dp[j], Math.min(dp[j-1], prev)) + 1; //temp is past dp[j] and prev is the past of the past dp[j]
                    maxEdge = Math.max(maxEdge, dp[j]); //and we need to get the max from all dp array
                } else {
                    dp[j] = 0; //this needs to be added, we can think of this a "reset dp[j] to 0", otherwise it it wrong
                }
                prev = temp; //we preserve the temp as prev
            }
        }
        return maxEdge * maxEdge;
    }
}
上一篇:1142 Maximal Clique (25 分)


下一篇:深度学习模型tensor维度对不上怎么办