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:
- 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]
题意
给定一个长度固定为8的数组,表示一排监狱房的状态。 其中 1 表有人, 0 表无人, 根据规则求出N天后这排监狱房的状态
思路
1. 对于nextday的状态,很好判断。 思路类似[leetcode]605. Can Place Flowers能放花吗
2.N为7,还可以板着手指一天一天的推算结果。但是看到Example2的N为十亿,发现不是板着手指数这么简单。
3.试着将N的值扩大,看看会发生什么,试探将N扩大为20,发现,
N = 14 时候cells的状态跟N= 0 时候一模一样,
N = 15 时候cells的状态跟N= 1 时候一模一样,
N = 16 时候cells的状态跟N= 2 时候一模一样
...
也就是说,14的时候出现了一个循环节。
代码
1 class Solution { 2 public int[] prisonAfterNDays(int[] cells, int N) { 3 HashSet<String> set = new HashSet<>(); 4 boolean hasCycle = false; 5 int count = 0; 6 for(int i = 0; i < N; i++){ 7 int[] next = nextDay(cells); 8 String s = Arrays.toString(next); 9 if(!set.contains(s)){ 10 set.add(s); 11 count ++; 12 }else{ 13 hasCycle = true; 14 break; 15 } 16 cells = next; 17 } 18 19 if(hasCycle){ 20 N = N % count; 21 for (int i = 0; i < N; i++){ 22 cells = nextDay(cells); 23 } 24 } 25 return cells; 26 } 27 28 public int[]nextDay (int[]cells){ 29 int[] temp = new int[cells.length]; 30 for(int i = 1; i < cells.length-1; i++){ 31 temp[i]=cells[i-1]==cells[i+1]?1:0; 32 } 33 return temp; 34 }