difference between `[[0] * n] * m` and `[[0 for _ in range(n)] for _ in range(m)]`

if change the declration of dp to, the solution breaks as updating any dp[row][col] updates all dp[:][col],ie the arrays for each row share memory.

dp = [[0] * n] * m

But this version works:

class Solution:
    def maximalSquare(self, matrix: List[List[str]]) -> int:
        m, n = len(matrix), len(matrix[0])
        dp = [[0 for _ in range(n)] for _ in range(m)]
        
        max_sq = 0
        for index in range(m):
            dp[index][0] = 1 if matrix[index][0] == '1' else 0
            max_sq = max(max_sq, dp[index][0])
            
        for index in range(n):
            dp[0][index] = 1 if matrix[0][index] == '1' else 0
            max_sq = max(max_sq, dp[0][index])
            
        for row in range(1, m):
            for col in range(1, n):
                if matrix[row][col] == '0':
                    continue
                    
                if matrix[row][col] == matrix[row-1][col] == matrix[row][col-1] == matrix[row-1][col-1] == '1':
                    dp[row][col] = min(dp[row-1][col], dp[row][col-1], dp[row-1][col-1]) + 1
                else:
                    dp[row][col] = 1
                    
             
                max_sq = max(max_sq, dp[row][col])

        return max_sq * max_sq

What is the difference between the two?
PS: Question: Maximal Square, leetcode 221

Comments (2)