957. Prison Cells After N Days
There are 8 prison cells in a row, and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
Each day, whether the cell is occupied or vacant changes according to the following rules:
- If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
- Otherwise, it becomes vacant.
(Note that because the prison is a row, the first and the last cells in the row can’t have two adjacent neighbors.)
We describe the current state of the prison in the following way: cells[i] == 1
if the i
-th cell is occupied, else cells[i] == 0
.
Given the initial state of the prison, return the state of the prison after N
days (and N
such changes described above.)
Example 1:
Input: cells = [0,1,0,1,1,0,0,1], N = 7 Output: [0,0,1,1,0,0,0,0] Explanation: The following table summarizes the state of the prison on each day: Day 0: [0, 1, 0, 1, 1, 0, 0, 1] Day 1: [0, 1, 1, 0, 0, 0, 0, 0] Day 2: [0, 0, 0, 0, 1, 1, 1, 0] Day 3: [0, 1, 1, 0, 0, 1, 0, 0] Day 4: [0, 0, 0, 0, 0, 1, 0, 0] Day 5: [0, 1, 1, 1, 0, 1, 0, 0] Day 6: [0, 0, 1, 0, 1, 1, 0, 0] Day 7: [0, 0, 1, 1, 0, 0, 0, 0]
Example 2:
Input: cells = [1,0,0,1,0,0,1,0], N = 1000000000 Output: [0,0,1,1,1,1,1,0]
Note:
cells.length == 8
cells[i]
is in{0, 1}
1 <= N <= 10^9
思路:连续8个牢房,每个牢房被占用或空置。每天,根据以下规则,单元是否被占用或空置变化:如果一个小区有两个相邻的邻居,它们都被占用或者都是空的,那么该小区就会被占用。否则,它会变空。请注意,因为监狱是一排,所以行中的第一个和最后一个单元格不能有两个相邻的邻居。我们用以下方式描述监狱的当前状态:如果第i个cell被占用,则cell [i] == 1,否则cells [i] == 0。鉴于监狱的初始状态,在N天之后返回监狱的状态(以及上述N个这样的改变。)
看到N=1000000000,思考一下应该是有循环的
看到N=1000000000,思考一下应该是有循环的
- 0 1 0 1 1 0 0 1
- 0 1 1 0 0 0 0 0
- 0 0 0 0 1 1 1 0
- 0 1 1 0 0 1 0 0
- 0 0 0 0 0 1 0 0
- 0 1 1 1 0 1 0 0
- 0 0 1 0 1 1 0 0
- 0 0 1 1 0 0 0 0
- 0 0 0 0 0 1 1 0
- 0 1 1 1 0 0 0 0
- 0 0 1 0 0 1 1 0
- 0 0 1 0 0 0 0 0
- 0 0 1 0 1 1 1 0
- 0 0 1 1 0 1 0 0
- 0 0 0 0 1 1 0 0
- 0 1 1 0 0 0 0 0
可以看出周期为14。
代码如下:
public class PrisonAfterNDays { public static int[] prisonAfterNDays(int[] cells, int N) { int n = 0; List<int[]> list = new ArrayList<>(); switchCells(cells, list, n); if (N < 14){ return list.get(N - 1); }else { if (N % 14 == 0){ return list.get(13); }else { return list.get(N % 14 - 1); } } } static void switchCells(int[] cells, List<int[]> list, int n){ n++; int[] temp = new int[8]; temp[0] = 0; temp[7] = 0; for (int i = 1; i < cells.length - 1; i++) { temp[i] = cells[i - 1] == cells[i + 1] ? 1 : 0; } list.add(temp); if (n < 14){ switchCells(temp, list, n); } } }