题目

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:

  1. Input: cells = [0,1,0,1,1,0,0,1], N = 7
  2. Output: [0,0,1,1,0,0,0,0]
  3. Explanation:
  4. The following table summarizes the state of the prison on each day:
  5. Day 0: [0, 1, 0, 1, 1, 0, 0, 1]
  6. Day 1: [0, 1, 1, 0, 0, 0, 0, 0]
  7. Day 2: [0, 0, 0, 0, 1, 1, 1, 0]
  8. Day 3: [0, 1, 1, 0, 0, 1, 0, 0]
  9. Day 4: [0, 0, 0, 0, 0, 1, 0, 0]
  10. Day 5: [0, 1, 1, 1, 0, 1, 0, 0]
  11. Day 6: [0, 0, 1, 0, 1, 1, 0, 0]
  12. Day 7: [0, 0, 1, 1, 0, 0, 0, 0]

Example 2:

  1. Input: cells = [1,0,0,1,0,0,1,0], N = 1000000000
  2. Output: [0,0,1,1,1,1,1,0]

Note:

  1. cells.length == 8
  2. cells[i] is in {0, 1}
  3. 1 <= N <= 10^9

题意

给定一个一维数组cells,进行N次循环,每次循环中如果cells[i]邻接的两个元素都为1或都为0,则cells[i]变为1,否则cells[i]变为0。首元素和末元素只会变为0。求N次循环后数组的状态。

思路

0289. Game of Life (M) 有点类似,每次状态的变更都是同时发生的,不能用前一个变化后的值去影响后一个将要改变的值。每次循环可以直接复制一个数组进行操作。同时,打表可以发现数组的状态是有规律的,以14作为一个周期,因此N等效于(N-1)%14+1。


代码实现

Java

  1. class Solution {
  2. public int[] prisonAfterNDays(int[] cells, int N) {
  3. N = (N - 1) % 14 + 1;
  4. for (int i = 1; i <= N; i++) {
  5. int[] aux = Arrays.copyOf(cells, 8);
  6. for (int j = 1; j < 7; j++) {
  7. cells[j] = aux[j - 1] == aux[j + 1] ? 1 : 0;
  8. }
  9. cells[0] = cells[7] = 0;
  10. }
  11. return cells;
  12. }
  13. }