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):
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.
For simplicity, let’s assume:
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:
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;
}
}
By following this strategy, we can efficiently compute the next generation of the board while modifying it in place.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?