1. 程式人生 > >LC 957. Prison Cells After N Days

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.)

 

使用字典記錄每一個過程和遍歷時的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 };