Description

According to the Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.”

Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population..
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.

Example:

Input: 
[
  [0,1,0],
  [0,0,1],
  [1,1,1],
  [0,0,0]
]
Output: 
[
  [0,0,0],
  [1,0,1],
  [0,1,1],
  [0,1,0]
]

Follow up:

  1. Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
  2. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?

Solutions

1. Array

# Time(mn)
# Space(1)
class Solution:
    def gameOfLife(self, board: List[List[int]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        if not board or not board[0]:
            return 

        r, c = len(board), len(board[0])
        for i in range(r):
            for j in range(c):
                cnt = 0
                for x in range(max(0, i - 1), min(i + 2, r)):
                    for y in range(max(0, j - 1), min(j + 2, c)):
                        if (x, y) != (i, j) and 1 <= board[x][y] <= 2:
                            cnt += 1
                if board[i][j] == 0:
                    if cnt == 3:
                        board[i][j] = 3
                else:
                    if cnt < 2 or cnt > 3:
                        board[i][j] = 2

        for i in range(r):
            for j in range(c):
                if board[i][j] == 2:
                    board[i][j] = 0
                elif board[i][j] == 3:
                    board[i][j] = 1
        # return board
# 23/23 cases passed (20 ms)
# Your runtime beats 99.7 % of python3 submissions
# Your memory usage beats 100 % of python3 submissions (12.7 MB)

  可以采用位操作继续优化一下,参考下面的链接。

References

  1. 289. Game of Life
  2. huahua
  3. Discuss