Leetcode 289. Game of Life

Problem

According to 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.”

The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 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.

The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state.

Algorithm

Code

class Solution:
    def gameOfLife(self, board: List[List[int]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        rows, cols = len(board), len(board[0])
        maps = [[0 for i in range(cols)] for j in range(rows)]
        dxy = [[1, 0], [1, 1], [1, -1], [0, 1], [0, -1], [-1, 0], [-1, 1], [-1, -1]]
        for r in range(rows):
            for c in range(cols):
                cnts = 0
                for k in range(8):
                    neighbor_r = r + dxy[k][0]
                    neighbor_c = c + dxy[k][1]
                    if neighbor_r >= 0 and neighbor_r < rows and neighbor_c >= 0 and neighbor_c < cols:
                        cnts += board[neighbor_r][neighbor_c]
                    if board[r][c] and cnts >= 2 and cnts <= 3 or not board[r][c] and cnts == 3:
                        maps[r][c] = 1
                    else:
                        maps[r][c] = 0
        
        for r in range(rows):
            for c in range(cols):
                board[r][c] = maps[r][c]

你可能感兴趣的:(Leetcode,解题报告,入门题,Leetcode,解题报告,算法)