LC 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:

  • 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

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]

题目要求:8个(0,1)一排,两边相同中间变1,两边不同中间变0。问N次后的数组样子。

思路1:使用字典记录每一个过程和遍历时的N,如果有重复直接取模。减少运算量。

 

 1 class Solution {
 2 public:
 3 vector<int> prisonAfterNDays(vector<int>& cells, int N) {
 4     unordered_map<string, int> map;
 5     string firstcell = "";
 6     for (int i = 0; i<cells.size(); i++) {
 7         firstcell += to_string(cells[i]);
 8     }
 9     while (N != 0) {
10         if (map.count(firstcell))
11             N %= map[firstcell] - N;
12         if(N == 0) break;
13         string nextstr = "";
14         for (int i = 1; i < 7; i++) {
15             nextstr += firstcell[i - 1] == firstcell[i + 1] ? "1" : "0";
16         }
17         nextstr = "0" + nextstr + "0";
18         //cout << nextstr << endl;
19         map[firstcell] = N;
20         firstcell = nextstr;
21         N--;
22     }
23     vector<int> ret;
24     for (int i = 0; i<firstcell.size(); i++) {
25         if (firstcell[i] == '0') ret.push_back(0);
26         else ret.push_back(1);
27     }
28     return ret;
29 }
30 };

 

posted @ 2018-12-17 23:58  yuxihong  阅读(324)  评论(0编辑  收藏  举报