Practice/Amazon/Leetcode 289. Game of Life
CodingMust
You are building a cellular automaton simulator. Given a 2D grid where each cell is either alive (represented by 1) or dead (represented by 0), compute the next generation of the grid according to these evolution rules:
Each cell has up to 8 neighbors: the cells directly adjacent horizontally, vertically, and diagonally.
The key challenge is that all cells must be evaluated simultaneously based on the current generation's state. You cannot update cells one-by-one because that would affect the neighbor counts for subsequent cells.
You should modify the grid in-place and return it.
m == grid.length (number of rows)n == grid[i].length (number of columns)1 <= m, n <= 25grid[i][j] is either 0 or 1Example 1:
` Input: grid = [ [0,1,0], [0,1,0], [0,1,0] ] Output: [ [0,0,0], [1,1,1], [0,0,0] ] Explanation:
Example 2:
Input: grid = [ [0,0,0,0], [0,1,1,0], [0,1,1,0], [0,0,0,0] ] Output: [ [0,0,0,0], [0,1,1,0], [0,1,1,0], [0,0,0,0] ] Explanation: This is a stable "block" pattern. Each living cell has exactly 3 neighbors, so they all survive. The dead cells don't have exactly 3 neighbors, so they stay dead.
Example 3:
Input: grid = [[0,0,0],[0,1,0],[0,0,0]] Output: [[0,0,0],[0,0,0],[0,0,0]] Explanation: The single cell has no neighbors and dies from underpopulation.