Count Square Submatrices with All Ones
LeetCode 1277 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
dp = 1 + min(up, left, diagonal); sum(dp) = number of squares.
ನಾನು Count Square Submatrices with All Ones (LeetCode 1277) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — DP on Squares / Matrix ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
dp[i][j] = side of the largest all-ones square whose bottom-right corner is (i, j). Such a square is limited by the squares ending just above, to the left and diagonally up-left. And a corner with value s means there are exactly s squares ending there (sizes 1..s), so summing dp counts them all.
Approach
- 1
Copy the first row and first column — they can only hold 1×1 squares.
- 2
For each other cell with a 1, take 1 + the min of its three neighbours.
- 3
Add every dp value to the count.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Square-corner DPPythonO(m·n) time · O(m·n) space
class Solution:
def countSquares(self, matrix: List[List[int]]) -> int:
m =len(matrix)
n = len(matrix[0])
dp=[[0]*n for _ in range(m)]
for i in range(m):
dp[i][0]=matrix[i][0]
for j in range(n):
dp[0][j]=matrix[0][j]
for i in range(1,m):
for j in range(1,n):
if matrix[i][j]==1:
dp[i][j]=min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1])+1
count=0
for i in range(m):
for j in range(n):
count+=dp[i][j]
return count
Count Square Submatrices with All Ones — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Count Square Submatrices with All Ones ಹಿಂದಿನ intuition ಏನು?
dp[i][j] = side of the largest all-ones square whose bottom-right corner is (i, j). Such a square is limited by the squares ending just above, to the left and diagonally up-left. And a corner with value s means there are exactly s squares ending there (sizes 1..s), so summing dp counts them all.
Count Square Submatrices with All Ones (LeetCode 1277) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Copy the first row and first column — they can only hold 1×1 squares. 2. For each other cell with a 1, take 1 + the min of its three neighbours. 3. Add every dp value to the count.
Count Square Submatrices with All Ones ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(m · n). Space: O(m · n). (Accepted approach: Square-corner DP.)
Count Square Submatrices with All Ones ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Cells with 0 stay 0 — they end no square.