Game of Life

Game of Life

another solution - 36ms

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
class Solution:
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if not board or not board[0]: return
m, n = len(board), len(board[0])
for i, row in enumerate(board):
for j, ele in enumerate(row):
count = 0
for a in range(max(0, i - 1), min(i + 2, m)):
for b in range(max(0, j - 1), min(j + 2, n)):
# skip i, j itself, (a, b) is (i, j)'s eight neighbors
# should count current_alive(1) and formerly_alive(2)
if (a, b) != (i, j) and 1 <= board[a][b] <= 2:
count += 1
if board[i][j] == 0:
if count == 3:
board[i][j] = 3
else:
if count < 2 or count > 3:
board[i][j] = 2
for i in range(m):
for j in range(n):
if board[i][j] == 2:
board[i][j] = 0
elif board[i][j] == 3:
board[i][j] = 1

test code

1
2
3
4
5
6
In [16]: in_arr = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
In [17]: s = Solution(); s.gameOfLife(in_arr)
In [18]: in_arr
Out[18]: [[0, 0, 0], [1, 0, 1], [0, 1, 1], [0, 1, 0]]

leet code

康威生命游戏