Demo entry 6642273

lq

   

Submitted by anonymous on Sep 22, 2017 at 17:36
Language: Python. Code size: 1.6 kB.

class Solution(object):
    def gameOfLife(self, board):
        """
        :type board: List[List[int]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        if not board:
            return [[]]
        # We will have a two bit representation of our state
        # The first bit will be 0 or 1 whether or not the cell will be alive next round
        # The next bit will be 0 or 1 whether or not the cell is alive this round
        def convert(i,j):
            candidates = filter(lambda t: not (t[0] == i and t[1] == j), 
                                [[x,y] for x in range(max(0, i - 1), min(len(board), i + 2))
                                                      for y in range(max(0, j - 1), min(len(board[0]), j + 2))])
            orig = board[i][j]
            live_count = reduce(lambda y, x: y + (1 if (board[x[0]][x[1]] % 2 == 1) else 0), candidates, 0)
            if orig == 1:
                if live_count < 2:
                    board[i][j] = board[i][j]
                elif live_count <= 3:
                    board[i][j] += 2
                else:
                    board[i][j] = board[i][j]
            else:
                if live_count == 3:
                    board[i][j] += 2
                else:
                    board[i][j] = board[i][j]
                
        for i in range(len(board)):
            for j in range(len(board[0])):
                convert(i,j)
        for i in range(len(board)):
            for j in range(len(board[0])):
                board[i][j] /= 2

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).