

def next_state(board):
    n = len(board)
    m = len(board[0])
    new = []
    for _ in xrange(n):
        new.append([0] * m)
    for i in xrange(n):
        for j in xrange(m):
            count = sum(
                (
                    board[i - 1][j - 1] if i > 0 and j > 0 else 0,
                    board[i - 1][j] if i > 0 else 0,
                    board[i - 1][j + 1] if i > 0 and j < m - 1 else 0,
                    board[i][j - 1] if j > 0 else 0,
                    board[i][j + 1] if j < m - 1 else 0,
                    board[i + 1][j - 1] if i < n - 1 and j > 0 else 0,
                    board[i + 1][j] if i < n - 1 else 0,
                    board[i + 1][j + 1] if i < n - 1 and j < m - 1 else 0
                )
            )
            if (board[i][j] and 2 <= count <= 3) or (not board[i][j] and count == 3):
                new[i][j] = 1
    for i in xrange(n):
        board[i] = new[i]


if __name__ == '__main__':
    board = [[0, 0, 0, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0]]
    next_state(board)
    print board
