LeetCode 289: Game of Life Solution
Master LeetCode problem 289 (Game of Life), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
289. Game of Life
Problem Explanation
Explanation
The problem requires updating the given board based on the rules of the Game of Life. We need to update the board in-place, considering the next state of each cell simultaneously. To do this, we can follow the following steps:
- Iterate through each cell in the board and calculate the number of live neighbors for each cell.
- Based on the current state of the cell and the number of live neighbors, update the cell to its next state according to the rules.
- To avoid updating cells and then using the updated values to update other cells, we can encode the next state in a different way. For example, we can use additional bits to represent the next state.
Time complexity: O(m*n) where m is the number of rows and n is the number of columns in the board. Space complexity: O(1) as we are updating the board in-place without using any additional data structures.
Solution Code
class Solution {
public void gameOfLife(int[][] board) {
int m = board.length;
int n = board[0].length;
int[][] directions = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int liveNeighbors = 0;
for (int[] dir : directions) {
int x = i + dir[0];
int y = j + dir[1];
if (x >= 0 && x < m && y >= 0 && y < n && (board[x][y] == 1 || board[x][y] == 2)) {
liveNeighbors++;
}
}
if (board[i][j] == 1 && (liveNeighbors < 2 || liveNeighbors > 3)) {
board[i][j] = 2; // cell dies
} else if (board[i][j] == 0 && liveNeighbors == 3) {
board[i][j] = 3; // cell becomes live
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
board[i][j] = board[i][j] % 2;
}
}
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 289 (Game of Life)?
This page provides optimized solutions for LeetCode problem 289 (Game of Life) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 289 (Game of Life)?
The time complexity for LeetCode 289 (Game of Life) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 289 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 289 in Java, C++, or Python.