Leetcode 289. Game of Life

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Game of Life

2. Solution

解析:Version 1,遍历所有细胞,统计其周围八个细胞的存活个数,根据规则判断当前细胞状态是否需要改变,如果需要,将其位置及要更新的状态保存到数组中,遍历数组,更新board即可。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m = len(board)
n = len(board[0])
cells = []
for i in range(m):
for j in range(n):
count = 0
if i > 0:
count += board[i-1][j]
if j > 0:
count += board[i-1][j-1]
if j < n - 1:
count += board[i-1][j+1]
if i < m - 1:
count += board[i+1][j]
if j > 0:
count += board[i+1][j-1]
if j < n - 1:
count += board[i+1][j+1]
if j > 0:
count += board[i][j-1]
if j < n - 1:
count += board[i][j+1]
if board[i][j] == 1 and (count < 2 or count > 3):
cells.append((i, j, 0))
if count == 3 and board[i][j] == 0:
cells.append((i, j, 1))
for x, y, state in cells:
board[x][y] = state

Reference

  1. https://leetcode.com/problems/game-of-life/
如果有收获,可以请我喝杯咖啡!