0
class Solution:
    def gameOfLife(self, board):
        return self.livingNeighbors(board)

    def livingNeighbors(self, board):
        m = len(board)
        n = len(board[0])
        nLivingNeighbor = [[0]*n]*m
        neighbors = [(-1,-1),(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1)]
        for i in range(m):
            for j in range(n):
                n_liv = 0
                for r,c in neighbors:
                    row = i + r
                    col = j + c
                    if (0 <= row < m) and (0<= col < n) and (board[row][col] == 1):
                        n_liv += 1
                print("n_liv = " + str(n_liv))
                nLivingNeighbor[i][j] = n_liv
        print(nLivingNeighbor)

        for i in range(m):
            for j in range(n):
                if board[i][j] == 1:
                    if nLivingNeighbor[i][j] < 2 or nLivingNeighbor[i][j] > 3:
                        board[i][j] = 0
                if board[i][j] == 0 and nLivingNeighbor[i][j] == 3:
                    board[i][j] = 1
        return board

I tried to update the elements in 2d list nLivingNeighbor by using nLivingNeighbor[i][j] = n_liv

And I used [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] to test the code. The result turned out to be

n_liv = 1
n_liv = 2
n_liv = 3
n_liv = 5
n_liv = 3
n_liv = 1
n_liv = 3
n_liv = 2
n_liv = 2
n_liv = 3
n_liv = 2
[[2, 3, 2], [2, 3, 2], [2, 3, 2], [2, 3, 2]]

n_livupdated in each iteration, however, all rows of nLivingNeighbor are the same. Is it because I didn't apply deep copy? How can I fix it?

Anthelion
  • 13
  • 2

0 Answers0