Fork me on GitHub

Game of Life

Description

https://leetcode.com/problems/game-of-life/description/

Solution

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):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if board is None or len(board) == 0:
return

directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
for i in range(len(board)):
for j in range(len(board[0])):
self.transform(i, j, board, directions)

for i in range(len(board)):
for j in range(len(board[0])):
board[i][j] >>= 1

def transform(self, x, y, board, directions):

count = 0
for direction in directions:
if direction[0] + x >= 0 and direction[0] + x < len(board) and \
direction[1] + y >= 0 and direction[1] + y < len(board[0]) and \
board[direction[0] + x][direction[1] + y] & 1 == 1:
count += 1

if (board[x][y] & 1) == 1:
if count == 2 or count == 3:
board[x][y] = board[x][y] + 2
else:
if count == 3:
board[x][y] = board[x][y] + 2