求解矩阵中最大全1正方形时出现错误,求技术支持
Hey there! Let's work through getting your maximal square solution sorted out. First off, I can see your code cuts off mid-line at matrix[i-...—that's definitely causing a syntax error right away. Let's break down the fix and get your dynamic programming (DP) approach working correctly.
Quick Recap of the DP Approach
For this problem, we use a DP array where dp[i][j] represents the side length of the largest square whose bottom-right corner is at position (i-1, j-1) in the original matrix. We add an extra row and column of zeros to the DP array to skip messy edge-case checks for the first row/column of the matrix. The key rules are:
- If the current matrix cell
matrix[i-1][j-1]is'1', thendp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1(this takes the smallest valid square from the top, left, and top-left neighbors, then extends it by one) - If the cell is
'0',dp[i][j]stays 0 since we can't form a square here.
Corrected Complete Code
def maximalSquare(matrix): """ :type matrix: List[List[str]] :rtype: int """ if len(matrix) == 0 or len(matrix[0]) == 0: return 0 maxlen = 0 # Initialize DP array with an extra row/column of zeros to avoid edge checks dp = [[0 for _ in range(len(matrix[0]) + 1)] for _ in range(len(matrix) + 1)] for i in range(1, len(matrix) + 1): for j in range(1, len(matrix[0]) + 1): # Check if current matrix cell is '1' (note: matrix elements are strings!) if matrix[i-1][j-1] == '1': # Calculate the largest square ending at this cell dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 # Update the maximum square length we've found maxlen = max(maxlen, dp[i][j]) # Return the area of the largest square (side length squared) return maxlen * maxlen
What Was Off in Your Original Code?
- Truncated Syntax: Your code cut off mid-condition, which throws an immediate syntax error. We completed that check to verify the current matrix cell is
'1'. - Missing DP Transition: You didn't implement the core calculation to set
dp[i][j]based on neighboring values. - Unupdated Maximum Length: You initialized
maxlenbut never updated it as you iterated through the matrix. - Edge Case Gap: We added a check for empty columns (in case the matrix has rows but no columns) to avoid index errors.
Example Test
If you run this code with the sample input:
matrix = [ ["1","0","1","0","0"], ["1","0","1","1","1"], ["1","1","1","1","1"], ["1","0","0","1","0"] ]
It will return 4—the area of the 2x2 square in the center, which is the correct expected result.
内容的提问来源于stack exchange,提问作者Rafael

