# 289 game of life

### 289. Game of Life

AC的效率还ok：

class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
def liveNeighbors(i,j):
return big[i-1][j-1] + big[i-1][j] + big[i-1][j+1] + big[i][j-1] + big[i][j+1] + big[i+1][j-1] + big[i+1][j] + big[i+1][j+1]

if board == [[]] : return
row = len(board)
col = len(board[0])

nbrs = [[0 for j in range(col)] for i in range(row)]
big = [[ 0 for j in range(col+2) ] for i in range(row+2)]
for i in range(1,row+1):
for j in range(1,col+1):
big[i][j] = board[i-1][j-1]

for i in range(1,row+1):
for j in range(1,col+1):
nbrs[i-1][j-1] = liveNeighbors(i,j)

for i in range(row):
for j in range(col):
if board[i][j] == 1:
if nbrs[i][j] < 2:
board[i][j] = 0
elif nbrs[i][j] == 2 or nbrs[i][j] == 3:
board[i][j] = 1
else:
board[i][j] = 0
else:
if nbrs[i][j] == 3:
board[i][j] = 1

https://www.hrwhisper.me/leetcode-game-of-life/

http://www.cnblogs.com/grandyang/p/4854466.html

class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
row = len(board)
col = len(board[0]) if row else 0

dx = [-1,-1,-1,0,1,1,1,0]
dy = [-1,0,1,1,1,0,-1,-1]

for i in range(row):
for j in range(col):
cnt = 0
for k in range(8):
x, y = i + dx[k], j + dy[k]
if x >=0 and x < row and y >=0 and y < col and (board[x][y] == 1  or board[x][y] == 2):
cnt += 1

if board[i][j] and (cnt < 2 or cnt > 3):
board[i][j] = 2
elif board[i][j] == 0 and cnt == 3:
board[i][j] = 3

for i in range(row):
for j in range(col):
board[i][j] %= 2

apachecn/AiLearning