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 above 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.
Here is the C++ code to solve the problem:
#include <vector>
using namespace std;
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
if (board.empty() || board[0].empty()) return;
int m = board.size();
int n = board[0].size();
// Make a copy of the original board to check the previous state
vector<vector<int>> copy = board;
// Directions array for the eight neighbors
vector<int> directions = {0, 1, -1};
for (int row = 0; row < m; ++row) {
for (int col = 0; col < n; ++col) {
int liveNeighbors = 0;
// Check all eight neighbors
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (directions[i] == 0 && directions[j] == 0) continue;
int r = row + directions[i];
int c = col + directions[j];
// Check the validity of cell and whether it was originally a live cell
if ((r < m && r >= 0) && (c < n && c >= 0) && (copy[r][c] == 1)) {
++liveNeighbors;
}
}
}
// Apply the Game of Life rules to determine the new state of the cell
if (copy[row][col] == 1 && (liveNeighbors < 2 || liveNeighbors > 3)) {
board[row][col] = 0; // Rule 1 or Rule 3
} else if (copy[row][col] == 0 && liveNeighbors == 3) {
board[row][col] = 1; // Rule 4
}
}
}
}
};
The solution iterates over all cells exactly once, and for each cell, it checks its eight neighbors. Therefore, the time complexity is:
m
is the number of rows and n
is the number of columns in the board.The space complexity is O(m * n) due to the use of a duplicate board.
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?