Cellular Automata
Time limit2sMemory limit1024 MB
Simulate all 64 update rules for g generations on the n by n grid and print the smallest rule that turns the start state into the end state.
- Level
Easy2 of 10
- Topics
- Brute force, Simulation
- Solved
- No attempts yet
Problem
A square field is divided into cells. Each cell holds one of two states, 0 or 1. At regular intervals called generations, every cell updates its state at the same time, based on the states that it and its neighbours held in the previous generation.
An interior cell has four neighbours: the cells above and below it, and the cells to its left and to its right. A corner cell has only two neighbours. The remaining cells along the edge of the field have three neighbours.
One way to update a cell is to look at the sum of the states that it and its neighbours held in the previous generation. That sum lies between 0 and 5, so an update rule fits in 6 bits. The rule 0 0 1 0 0 1, for instance, says that the new state of a cell is
- 0 if the sum was 5,
- 0 if the sum was 4,
- 1 if the sum was 3,
- 0 if the sum was 2,
- 0 if the sum was 1,
- 1 if the sum was 0,
where the sum means the sum of the previous states of the cell and of all its neighbours. Each rule is identified by its binary code: the 6 bits correspond to the decimal value . The rule above has the binary number 001001, so its decimal value is 9.
Take with the starting state
1111
1111
1111
1111
Rule 9 turns it into
1001
0000
0000
1001
after one generation, and into
0000
0110
0110
0000
after two generations.
Given a size , a number of generations , a starting state and an ending state , find the rule with the smallest decimal value that turns into after exactly generations.
is at most 30 and is at most 50.
Input
The input consists of the following lines.
- The first line contains two positive integers, the size and the number of generations .
- Each of the next lines contains digits, each of them 0 or 1. These lines give the starting state .
- The next line is empty.
- Each of the following lines contains digits, each of them 0 or 1. These lines give the ending state .
Output
Print a single integer, the smallest decimal value of a rule that turns into after exactly generations. Print -1 if no rule does this.