Game of Life
Problem: Game of Life
To play game of life in place, we can use extra numbers to represent future status and current status at the same time. We can use number 2 to represent a dead cell going to become a live cell and number 3 to represent a dying live cell. Thus we can do update after checking the whole map.
Code in Python:
class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
rows, cols = len(board), len(board[0])
board[:] = [[0] * cols] + board[:] + [[0] * cols]
for i in xrange(1, rows+1):
for j in xrange(cols):
sum = board[i-1][j]%2 + board[i+1][j]%2
if j > 0:
sum += board[i-1][j-1]%2 + board[i][j-1]%2 + board[i+1][j-1]%2
if j < cols - 1:
sum += board[i-1][j+1]%2 + board[i][j+1]%2 + board[i+1][j+1]%2
if not board[i][j] and sum == 3:
board[i][j] = 2
elif board[i][j] and (sum > 3 or sum < 2):
board[i][j] = 3
board[:] = board[1:rows+1]
for i in xrange(rows):
for j in xrange(cols):
if board[i][j] == 2: board[i][j] = 1
if board[i][j] == 3: board[i][j] = 0