# 289. Game of Life

According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."

Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

Any live cell with fewer than two live neighbors dies, as if caused by under-population.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by over-population.
Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.

Example:

Input: 
[
  [0,1,0],
  [0,0,1],
  [1,1,1],
  [0,0,0]
]
Output: 
[
  [0,0,0],
  [1,0,1],
  [0,1,1],
  [0,1,0]
]

Follow up:

  • Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
  • In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?

# Solution

Approach 1: idea for in place: use 2 digits ('00', '01', '10', '11') (or 3 and 4) as the intermediate state. Infinite board: represent the board as a list of coords of live cells (if sparse), or read the input line by line if too large to fit into memory.

Approach 2: Save the original data in a buffer (two rows would be enough).l

# Code (Python)

Approach 1:

class Solution:
    def gameOfLife(self, board: List[List[int]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """   
        rules = {
            '11': lambda neighbors: '10' if neighbors in [0, 1] + list(range(4, 9)) else '11',
            '00': lambda neighbors: '01' if neighbors == 3 else '00'
        }
        
        # preprocess
        for i in range(len(board)):
            for j in range(len(board[0])):
                board[i][j] = str(board[i][j]) * 2
        
        # update
        for i in range(len(board)):
            for j in range(len(board[0])):
                board[i][j] = rules[board[i][j]](self._num_live_neighbors(i, j, board))

        # postprocess
        for i in range(len(board)):
            for j in range(len(board[0])):
                board[i][j] = int(board[i][j][1])
    
    def _num_live_neighbors(self, i, j, board):
        num = 0
        for delta_i, delta_j in ((-1, 1), (-1, -1), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (1, 0)):
            if 0 <= i + delta_i < len(board) and 0 <= j + delta_j < len(board[0]):
                num += board[i+delta_i][j+delta_j][0] == '1'
        return num

# Code (C++)

Approach 1:

// 0: 0->0
// 1: 1->1
// 2: 1->0
// 3: 0->1
class Solution {
private:
    int getStatus(vector<vector<int>>& board, int i, int j) {
        if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size())
            return 0;
        if (board[i][j] == 1 || board[i][j] == 2)
            return 1;
        return 0;
    }
public:
    void gameOfLife(vector<vector<int>>& board) {
        int m = board.size();
        int n = board[0].size();
        for (int i = 0; i < m; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                int liveCount =
                    getStatus(board, i-1, j-1) +
                    getStatus(board, i-1, j) +
                    getStatus(board, i-1, j+1) +
                    getStatus(board, i, j-1) +
                    getStatus(board, i, j+1) +
                    getStatus(board, i+1, j-1) +
                    getStatus(board, i+1, j) +
                    getStatus(board, i+1, j+1);
                if (board[i][j] && (liveCount < 2 || liveCount > 3))
                    board[i][j] = 2;
                else if (!board[i][j] && liveCount == 3)
                    board[i][j] = 3;

            }
        }
        for (int i = 0; i < m; ++i)
            for (int j = 0; j < n; ++j)
                board[i][j] %= 2;
    }
};

Approach 2:

// Use to rows of buffer.
class Solution {
private:
    int getStatus(vector<vector<int>>& board, vector<int>&tmp, vector<int>&buf, int row, int i, int j) {
        if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size())
            return 0;
        if (row > i)
            return tmp[j];
        else if (row == i)
            return buf[j];
        return board[i][j];
    }
public:
    void gameOfLife(vector<vector<int>>& board) {
        int m = board.size();
        int n = board[0].size();
        vector<int> tmp = vector<int>(n, 0);
        for (int i = 0; i < m; ++i)
        {
            vector<int> buf;
            for (int j = 0; j < n; ++j)
            {
                buf.push_back(board[i][j]);
            }
            for (int j = 0; j < n; ++j)
            {
                int liveCount =
                    getStatus(board, tmp, buf, i, i-1, j-1) +
                    getStatus(board, tmp, buf, i, i-1, j) +
                    getStatus(board, tmp, buf, i, i-1, j+1) +
                    getStatus(board, tmp, buf, i, i, j-1) +
                    getStatus(board, tmp, buf, i, i, j+1) +
                    getStatus(board, tmp, buf, i, i+1, j-1) +
                    getStatus(board, tmp, buf, i, i+1, j) +
                    getStatus(board, tmp, buf, i, i+1, j+1);
                if (board[i][j] && (liveCount < 2 || liveCount > 3))
                    board[i][j] = 0;
                else if (!board[i][j] && liveCount == 3)
                    board[i][j] = 1;
            }
            for (int j = 0; j < n; ++j)
            {
                tmp[j] = buf[j];
            }
        }
    }
};