I'm a beginner in Python. The following is my code for leetcode 221 (Maximal Square), it can only pass more than 30 test samples. It fails at the matrix: M=[["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
.
def maximalSquare(matrix):
colleng=len(matrix)
rowleng=len(matrix[0])
maxsqlst=[]
dp=[[0]*rowleng]*colleng
for i in range(colleng):
for j in range(rowleng):
if matrix[i][j]=='1':
if i==0 or j==0:
print('A',i,j,dp)
dp[i][j]=1
print('B',i,j,dp)
else:
dp[i][j]=min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1
print(i,j,dp)
maxsqlst.append(max(dp[i]))
return max(maxsqlst)**2
By inserting some print()
command, I find that it goes wrong when i=j=0,
A 0 0 [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
B 0 0 [[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]].
Why does it make the first colume to be 1 instead of just dp[0][0]?