algoadvance

Leetcode 289. Game of Life

Problem Statement

The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.

The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the Wikipedia article):

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

The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state.

Clarifying Questions

  1. Input Constraints:
    • What are the allowed dimensions of the grid? (e.g., minimum and maximum values of m and n)
    • Are there any constraints on the initial state of the board? (e.g., all values are either 0 or 1)
  2. Output Format:
    • Should the output modify the input grid in place, or can a new grid be created?

For simplicity, let’s assume:

Strategy

To solve this problem, we need to keep track of the state of each cell while simultaneously applying the rules to generate the next state. Given the requirement to modify the board “in place,” we’ll need a strategy to record changes without interfering with the current state.

Implementation Strategy:

  1. Neighbor Counting: For each cell, count the number of live neighbors (cells that are in the “1” state).
  2. State Transition: Use the neighbor count to determine the next state for each cell based on the provided rules.
  3. In-place Modification: To achieve in-place modifications without losing the current state information:
    • Use different integer values to mark transitions:
      • 0 -> 1: mark as 2
      • 1 -> 0: mark as -1
  4. Final Update: Iterate through the board again and transform marked cells to their final states.

Code

public class GameOfLife {
    private static final int LIVE_TO_DEAD = -1;
    private static final int DEAD_TO_LIVE = 2;

    public void gameOfLife(int[][] board) {
        int m = board.length;
        int n = board[0].length;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int liveNeighbors = countLiveNeighbors(board, i, j, m, n);
                
                if (board[i][j] == 1 && (liveNeighbors < 2 || liveNeighbors > 3)) {
                    board[i][j] = LIVE_TO_DEAD;
                } else if (board[i][j] == 0 && liveNeighbors == 3) {
                    board[i][j] = DEAD_TO_LIVE;
                }
            }
        }

        // Final update
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == LIVE_TO_DEAD) {
                    board[i][j] = 0;
                } else if (board[i][j] == DEAD_TO_LIVE) {
                    board[i][j] = 1;
                }
            }
        }
    }

    private int countLiveNeighbors(int[][] board, int row, int col, int m, int n) {
        int liveNeighbors = 0;
        int[] directions = {-1, 0, 1};

        for (int dr : directions) {
            for (int dc : directions) {
                if (dr == 0 && dc == 0) continue;
                int newRow = row + dr;
                int newCol = col + dc;
                if (newRow >= 0 && newRow < m && newCol >= 0 && newCol < n 
                    && (board[newRow][newCol] == 1 || board[newRow][newCol] == LIVE_TO_DEAD)) {
                    liveNeighbors++;
                }
            }
        }
        return liveNeighbors;
    }
}

Time Complexity

By following this strategy, we can efficiently compute the next generation of the board while modifying it in place.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI