Game of Life

Turn a board of live and dead cells into its next generation in place, using a spare bit in each cell.

Conway's Game of Life is played on a board of cells, where each cell is live (1) or dead (0). The neighbours of a cell are the cells touching it: above, below, left, right and on the four diagonals, eight in all away from the edges. The next generation comes from two rules, applied to every cell at the same time:

Given the board as an int[][] array, change it in place into the next generation.

Example 1
Input: board = [[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]]
Example 2
Input: board = [[1, 1], [1, 0]]
Output: [[1, 1], [1, 1]]
Solution

The Idea

The Game of Life is a tiny model of a population. A live cell needs some company to survive, but it dies when it is alone or crowded. A new cell appears on an empty spot where exactly three live cells meet. One step of the game turns the whole board into the next generation.

Take Example 1 and look at the cell in row 1, col 0. It is dead now. Around it are five cells on the board, and three of them are live: (row 0, col 1), (row 2, col 0) and (row 2, col 1). Exactly three, so it is born, and the output has a 1 there.

Now look at row 0, col 1. It is live, but its only live neighbour is row 1, col 2, so it dies. Here is the catch. Going row by row, this cell is handled first. If we write its 0 into the board straight away, row 1, col 0 later counts only two live neighbours and is never born.

So every cell has to keep its state now until all its neighbours have counted it, and also hold its state next somewhere. Where can both fit without a second board? Inside the cell itself. A Java int has 32 bits, and a 0 or 1 uses only the lowest one. The bit next to it is free.

Bits are counted from the right, starting at position 0. The board stores the state now in bit 0, and the state next can go into bit 1. The value 2, for example, is written 10 in binary: a 1 in bit 1 and a 0 in bit 0. It means "dead now, live next". The picture shows Example 1 before and after the cells get their bit 1.

Left, the Example 1 board with rows 0 to 3 and columns 0 to 2. A dashed box around row 1, col 0 shows its neighbours, three of them live. Right, the same board after the first pass, each cell written as two binary digits: bit 1 is the state next and bit 0 the state now. Row 1, col 0 holds 10.

On the left, the dashed box holds row 1, col 0 and its neighbours, with the three live ones in blue. On the right, under "after the first pass", the same cell holds 10: its right digit still says dead now, and its left digit says live next. Row 0, col 1 holds 01, live now and dead next. Any neighbour that reads only the right digit still sees the board as it was. The teal cells are the ones that live in the next generation.

Solution Approach

The code has three jobs: count each cell's live neighbours, store the next states somewhere (first in a plain copy of the board, then in the spare bit), and make the next states the current ones.

Counting the neighbours

How do we visit the cells around row r, col c? Two small loops, with dr and dc each running from -1 to 1, give the nine cells of the 3-by-3 square centred on it. The centre, where both are 0, is the cell itself and is skipped. Cells that would fall off the board are skipped too, which is why row 1, col 0 in Example 1 has five neighbours, not eight.

The two rules then fold into one test. A cell lives next if it has exactly 3 live neighbours, whether it is live or dead now, or if it is live now and has exactly 2.

Keeping a copy of the board

What is the simplest place for the next states? A second int[][] of the same size. Count on the original, write into the copy, then copy the results back. It works, but it needs as much extra memory as the board itself, and the problem asks for an update in place.

Two states in one cell

How do we read and write single bits? To read the state now, board[r][c] & 1 keeps only bit 0. For the cell in row 1, col 0 after the first pass, that is 2 & 1, which is 0, so it still counts as dead. For row 1, col 2 it is 3 & 1, which is 1.

To mark a cell as live next, board[r][c] |= 2 sets bit 1 and leaves bit 0 alone: a 0 becomes 2 and a 1 becomes 3. Cells that will be dead next need no write, because bit 1 is already 0.

Switching to the next generation

Once every cell has its bit 1, how does it become the state now? A second pass shifts every value one bit to the right with >>= 1. Bit 1 moves into bit 0 and the old bit 0 drops off: 3 and 2 both become 1, while 1 and 0 become 0.

Java Solution

The method gameOfLife works in these steps:

  1. First, read the board's size into rows and cols.
  2. Visit every cell with two loops, one inside the other: the outer loop moves r over the rows, and the inner loop moves c over the columns.
  3. For each cell, count its live neighbours into live. Two more loops run dr and dc from -1 to 1, giving the neighbour position nr, nc. The flag self marks the cell itself; it is skipped, along with positions off the board, and every other neighbour adds board[nr][nc] & 1.
  4. Read the cell's own state now into alive. If live is 3, or alive is true and live is 2, set bit 1 with board[r][c] |= 2.
  5. After the first pass, a second pair of loops shifts every cell right by one bit with board[r][c] >>= 1.

The main method prints each board before and after one step, for both examples, a lone live cell, and three live cells in a row.

Java
public class GameOfLife {

    // Bit 0 of a cell holds its state now, bit 1 its state in the next generation.
    public static void gameOfLife(int[][] board) {
        int rows = board.length;
        int cols = board[0].length;
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                int live = 0;
                for (int dr = -1; dr <= 1; dr++) {
                    for (int dc = -1; dc <= 1; dc++) {
                        int nr = r + dr;
                        int nc = c + dc;
                        boolean self = dr == 0 && dc == 0;
                        if (!self && nr >= 0 && nr < rows && nc >= 0 && nc < cols) {
                            live += board[nr][nc] & 1;      // read only the state now
                        }
                    }
                }
                boolean alive = (board[r][c] & 1) == 1;
                if (live == 3 || (alive && live == 2)) {
                    board[r][c] |= 2;                       // lives in the next generation
                }
            }
        }
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                board[r][c] >>= 1;                          // next state moves into bit 0
            }
        }
    }

    static void run(String name, int[][] board) {
        System.out.println(name + ", before:");
        print(board);
        gameOfLife(board);
        System.out.println("after:");
        print(board);
        System.out.println();
    }

    static void print(int[][] board) {
        for (int[] row : board) {
            System.out.println("  " + java.util.Arrays.toString(row));
        }
    }

    public static void main(String[] args) {
        run("Example 1", new int[][] {{0, 1, 0}, {0, 0, 1}, {1, 1, 1}, {0, 0, 0}});
        run("Example 2", new int[][] {{1, 1}, {1, 0}});
        run("A lone cell", new int[][] {{1}});
        run("Three in a row", new int[][] {{0, 0, 0}, {1, 1, 1}, {0, 0, 0}});
    }
}

Running it prints:

Output
Example 1, before:
  [0, 1, 0]
  [0, 0, 1]
  [1, 1, 1]
  [0, 0, 0]
after:
  [0, 0, 0]
  [1, 0, 1]
  [0, 1, 1]
  [0, 1, 0]

Example 2, before:
  [1, 1]
  [1, 0]
after:
  [1, 1]
  [1, 1]

A lone cell, before:
  [1]
after:
  [0]

Three in a row, before:
  [0, 0, 0]
  [1, 1, 1]
  [0, 0, 0]
after:
  [0, 1, 0]
  [0, 1, 0]
  [0, 1, 0]

In Example 1, row 1 after the step reads [1, 0, 1]. The 1 at col 0 is the birth from the picture, and the top row is all zeros because row 0, col 1 died. In Example 2, the dead corner at row 1, col 1 touches the other three cells, all live, so it is born and the board fills up.

The lone cell has no neighbours at all, so it dies and prints [0]. The three cells in a row turn into a column. The middle one, row 1, col 1, has 2 live neighbours and stays. Row 0, col 1 and row 2, col 1 each touch all three and are born, while the two ends, with one live neighbour each, die.

Reading only bit 0 is what keeps Example 1 right. A separate test program wrote each new state straight back as 0 or 1 in a single pass, and Example 1 came out as [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 0, 0]]. Row 1, col 0 is missing, because row 0, col 1 had already been set to 0 when it was counted.

Complexity

The board is read in two passes, and the first one looks at a fixed 3-by-3 square around each cell.

  • Time: O(m × n) for a board of m rows and n columns, because the first pass checks at most 8 neighbours for each of the m × n cells and the second pass shifts each cell once.
  • Space: O(1), because the next generation lives in bit 1 of each cell's own int, so no copy of the board is made.

Another in-place matrix update where the order of writes needs care is Set Matrix Zeroes.