本文主要是介绍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):
- Any live cell with fewer than two live neighbors dies as if caused by under-population.
- Any live cell with two or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies, as if by over-population.
- 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 = 0for 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] = 1else:maps[r][c] = 0for r in range(rows):for c in range(cols):board[r][c] = maps[r][c]
这篇关于Leetcode 289. Game of Life的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!