Skip to content

1277. Count Square Submatrices with All Ones #755

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We can use Dynamic Programming (DP) to keep track of the number of square submatrices with all ones that can end at each cell in the matrix. Here's the approach to achieve this:

  1. DP Matrix Definition:

    • Define a DP matrix dp where dp[i][j] represents the size of the largest square submatrix with all ones that has its bottom-right corner at cell (i, j).
  2. Transition Formula:

    • For each cell (i, j) in the matrix:
      • If matrix[i][j] is 1, the value of dp[i][j] depends on the minimum of the squares that can be formed by extending from (i-1, j), (i, j-1), and (i-1, j-1). The transition formula is:
        dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
        
      • If matrix[i][j] is 0, dp[i][j] will be 0…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@basharul-siddike
Comment options

@mah-shamim
Comment options

mah-shamim Oct 27, 2024
Maintainer Author

Answer selected by basharul-siddike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty hacktoberfest hacktoberfest hacktoberfest-accepted hacktoberfest accepted
2 participants