Game of Life

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:

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.

  • Time: O(n)
  • Space: O(1)

00 dead <- dead
01 dead <- live
10 live <- dead
11 live <- live

public void gameOfLife(int[][] board) {
    int m = board.length, n = board[0].length;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            int count = getLiveNeighbour(i, j, board);
            if (board[i][j] == 0 && count == 3) {
                board[i][j] = 2;
            }
            if (board[i][j] == 1 && (count == 2 || count == 3)) {
                board[i][j] = 3;
            }
        }
    }
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            board[i][j] >>= 1;
        }
    }
}

private int getLiveNeighbour(int x, int y, int[][] board) {
    int count = 0;
    int m = board.length, n = board[0].length;
    for (int i = Math.max(x - 1, 0); i <= Math.min(x + 1, m - 1); i++) {
        for (int j = Math.max(y - 1, 0); j <= Math.min(y + 1, n - 1); j++) {
            count += board[i][j] & 1;
        }
    }
    count -= board[x][y] & 1;
    return count;
}

results matching ""

    No results matching ""