Maximal Square

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

Example

For example, given the following matrix:

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

Return 4.

Notes:

  1. Represents square: right-bottom corner axis and the the length of edge
  2. DP
  3. Optimize by Rolling Array, remember to reset the state when the condition is not met.
    public int maxSquare(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
            return 0;
        }

        int m = matrix.length;
        int n = matrix[0].length;

        int[][] f = new int[2][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] == 1) {
                    f[i%2][j] = Math.min(f[(i-1)%2][j-1], Math.min(f[(i-1)%2][j], f[i%2][j-1]))+1;
                } else {
                    f[i%2][j] = 0;
                }
                max = Math.max(max, f[i%2][j]);
            }
        }

        return max*max;
    }

results matching ""

    No results matching ""