#K81142. Game of Life: Next State Generation
Game of Life: Next State Generation
Game of Life: Next State Generation
You are given a grid representing the current state of Conway's Game of Life. Your task is to compute the next state of the grid according to the following rules:
- Any live cell (represented by a 1) with fewer than 2 live neighbours dies, as if by underpopulation.
- Any live cell with 2 or 3 live neighbours lives on to the next generation.
- Any live cell with more than 3 live neighbours dies, as if by overpopulation.
- Any dead cell (represented by a 0) with exactly 3 live neighbours becomes a live cell, as if by reproduction.
In mathematical terms, let \(N(c)\) be the number of live neighbours of a cell. Then:
- If the cell is live: it remains live if \(2 \leq N(c) \leq 3\); otherwise it dies.
- If the cell is dead: it becomes live if \(N(c) = 3\); otherwise it remains dead.
The grid is provided as a 2D array with R rows and C columns. The first line of input contains two integers: R and C, followed by R lines each containing C space-separated integers.
Your program should output the next state of the grid in the same format.
inputFormat
The input starts with a line containing two integers R and C (the number of rows and columns). The next R lines each contain C integers (each either 0 or 1) separated by spaces, representing the current state of the grid.
Example:
4 3 0 1 0 0 0 1 1 1 1 0 0 0
outputFormat
Output the next state of the grid with the same dimensions. Each of the R lines should contain C space-separated integers.
For the input above, the correct output is:
0 0 0 1 0 1 0 1 1 0 1 0## sample
4 3
0 1 0
0 0 1
1 1 1
0 0 0
0 0 0
1 0 1
0 1 1
0 1 0
</p>