Python中的生命游戏,为什么我的temp_board不是我所期望的?

时间:2016-10-28 23:52:03

标签: python algorithm conways-game-of-life

我正在努力解决康威的生活游戏,但我想我已经陷入了困境。我正在计算周围的细胞,我认为我正确地得到它。但是,当我将这些数字分配给temp_board并且当我打印temp_board时,值都是错误的。

我将它放入temp_board进化到下一代。我知道这不是最好的代码,但我正在尝试迭代,所以我试图以最简单的方式首先解决它。

class Solution(object):
    def gameOfLife(self, board):
        """
        :type board: List[List[int]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        m = len(board)
        n = len(board[0]) if m else 0

        temp_board = [[0] * n] * m

        def count_cell(i, j):
          list_of_tuples = [(i-1, j-1), (i-1, j), (i-1, j+1),
              (i, j-1), (i, j), (i, j+1),
              (i+1, j-1), (i+1, j), (i+1, j+1)]

          count = 0
          for l in list_of_tuples:
            x, y = l
            if x >= 0 and y >= 0 and x < m and y < n:
              if x is not i or y is not j:
                if board[x][y] == 1:
                  count += 1

          return count

        for i in range(m):
          for j in range(n):
            cell = board[i][j]
            count = count_cell(i, j)
            temp_board[i][j] = count
            #print('(%s, %s) has %s' % (i, j, count))
        print(temp_board)

"""
            if cell == 1:
              if count < 2:
                temp_board[i][j] = 0
              elif count is 3 or count is 2:
                temp_board[i][j] = 1
              elif count > 3:
                temp_board[i][j] = 0
            else:
              if count == 3:
                temp_board[i][j] = 1
        """

board = [[0,0,0,0,0],
    [0,0,1,0,0],
    [0,0,1,0,0],
    [0,0,1,0,0],
    [0,0,0,0,0]]

Solution().gameOfLife(board)

这是结果

➜  game-of-life git:(master) ✗ python main.py
0
1
1
1
0
0
2
1
2
0
0
3
2
3
0
0
2
1
2
0
0
1
1
1
0
[[0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0]]

奇怪的是,当我打印每个细胞计数时,它都是正确的。但是当我打印temp_board时,一切都错了。我敢肯定我会错过一些明显的东西。

0 个答案:

没有答案