LeetCode 1277: Count Square Submatrices with All Ones Solution

Master LeetCode problem 1277 (Count Square Submatrices with All Ones), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1277. Count Square Submatrices with All Ones

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming. We create a 2D DP array where each cell (i, j) represents the size of the largest square with all ones with bottom-right corner at (i, j).

For each cell (i, j) in the matrix:

  • If matrix[i][j] is 0, the largest square with all ones ending at this cell will be 0.
  • If matrix[i][j] is 1, we look at the values of (i-1, j), (i, j-1), and (i-1, j-1) in the DP array to determine the size of the square ending at (i, j).

The total number of squares with all ones is the sum of all values in the DP array.

Time complexity: O(mn) where m is the number of rows and n is the number of columns in the input matrix. Space complexity: O(mn) for the DP array.

Solution Code

class Solution {
    public int countSquares(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int[][] dp = new int[m][n];
        int count = 0;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == 1) {
                    if (i == 0 || j == 0) {
                        dp[i][j] = 1;
                    } else {
                        dp[i][j] = Math.min(dp[i-1][j], Math.min(dp[i][j-1], dp[i-1][j-1])) + 1;
                    }
                    count += dp[i][j];
                }
            }
        }

        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1277 (Count Square Submatrices with All Ones)?

This page provides optimized solutions for LeetCode problem 1277 (Count Square Submatrices with All Ones) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1277 (Count Square Submatrices with All Ones)?

The time complexity for LeetCode 1277 (Count Square Submatrices with All Ones) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1277 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1277 in Java, C++, or Python.

Back to LeetCode Solutions