Maximal Square
LeetCode 221 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
dp = 1 + min(up, left, diagonal); answer = max side².
ನಾನು Maximal Square (LeetCode 221) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — DP on Squares / Matrix ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Same corner DP as counting squares: dp[i][j] is the largest all-'1' square ending at (i, j), limited by the three neighbouring squares. Track the biggest side and return its area.
Approach
- 1
Seed the first row and column from the matrix (characters → ints).
- 2
For other '1' cells, dp = 1 + min of the three neighbours.
- 3
Track the largest side and return side × side.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Square-corner DPPythonO(m·n) time · O(m·n) space
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
#dp[i][j]=min(dp[i-1][j-1],dp[i-1][j],dp[i][j-1])+1
m = len(matrix)
n = len(matrix[0])
max_sq = 0
dp = [[0]*n for _ in range(m)]
for i in range(m):
dp[i][0]= int(matrix[i][0])
max_sq= max(max_sq,dp[i][0])
for j in range(n):
dp[0][j]=int(matrix[0][j])
max_sq= max(max_sq,dp[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
max_sq=max(max_sq,dp[i][j])
return max_sq*max_sqMaximal Square — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Maximal Square ಹಿಂದಿನ intuition ಏನು?
Same corner DP as counting squares: dp[i][j] is the largest all-'1' square ending at (i, j), limited by the three neighbouring squares. Track the biggest side and return its area.
Maximal Square (LeetCode 221) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Seed the first row and column from the matrix (characters → ints). 2. For other '1' cells, dp = 1 + min of the three neighbours. 3. Track the largest side and return side × side.
Maximal Square ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(m · n). Space: O(m · n). (Accepted approach: Square-corner DP.)
Maximal Square ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
The matrix holds characters '0'/'1', not integers. Return the area, not the side.