Start free

Expert · Simulation · 257 of 264

Game of Life

Conway's Game of Life on a grid (cells outside the grid are dead). A live cell (#) with 2 or 3 live neighbours stays alive; a dead cell (.) with exactly 3 becomes alive; all others die or stay dead. Neighbours are the 8 cells around.

Input: r, c and the number of generations, then r lines. Output: the grid after that many generations.

Examples

Input
5 5 1
.....
..#..
..#..
..#..
.....
Output
.....
.....
.###.
.....
.....
Input
4 4 3
....
.##.
.##.
....
Output
....
.##.
.##.
....
Input
6 6 4
.#....
..#...
###...
......
......
......
Output
......
..#...
...#..
.###..
......
......

One more test checks other inputs when you press Check.

Stuck? The idea behind simulation

Follow the rules step by step, exactly as written: keep the state (a grid, a position), and work out the next state from the current one.

When every cell changes at once, build the new grid apart from the old one.

x, y = 0, 0
for move in "NNEES":
    x += {"E": 1, "W": -1}.get(move, 0)
    y += {"N": 1, "S": -1}.get(move, 0)
print(x, y)

Watch for: Changing the grid while still reading it mixes this step with the next.

All the simulation exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More simulation exercises