Link

Medium DP

Amazon

Apple

Bloomberg

Google

Huawei

Uber

2020-05-21

221. Maximal Square

Similar Question: LeetCode Question 1277

Question:

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

Example:

Input: 

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

Output: 4

Solution:

Using DP to solve the problem. The DP function is dp[i][j] = min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]). The DP means that the side length of the square with right bottom point ends at matrix[i][j]

The following solution using O(1) space, but require cast from integer to character and from character to integer.

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