假设连续有8个牢房,每个牢房中有一个囚犯,或者是空的。每天,牢房是否有人居住都根据以下规则进行更改-
如果一个单元有两个相邻的邻居都被占用或都空闲,则该单元将被占用。
否则,它将变为空。
我们将通过以下方式描述监狱的当前状态:如果第i个牢房被占用,则cell [i]将为1,否则,cells [i]将为0。
因此,我们具有初始的监狱状态,然后在N天后返回监狱的状态。
因此,如果输入为:[0,1,0,1,1,0,0,1],并且N = 7,则输出将为[0,0,1,1,0,0,0, 0]。因此,这是由于以下原因。七天-
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]
为了解决这个问题,我们将遵循以下步骤-
创建一个映射m,然后创建一个称为Visited的集合。
如果N为0,则返回单元格
将单元格插入访问集中
对于我在1到14之间的范围
如果cell [j – 1] XOR cells [j + 1] = 0,则temp [j]:= 1
创建一个名为temp 8的数组
对于1到6范围内的j
单元格:=临时
m [i]:=温度
将temp插入访问
如果N被14整除,则返回m [14],否则返回m [N mod 14]
让我们看下面的实现以更好地理解-
#include <bits/stdc++.h> using namespace std; void print_vector(vector<int> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int> prisonAfterNDays(vector<int>& cells, int N) { map <int, vector <int> > m; if(N == 0) return cells; set <vector <int> > visited; visited.insert(cells); for(int i = 1; i<=14 ; i++ ){ vector <int> temp(8); for(int j = 1; j < 7; j++){ if(cells[j - 1] ^ cells[j + 1] == 0){ temp[j] = 1; } } cells = temp; m[i] = temp; visited.insert(temp); } return m[N % 14 == 0? 14 : N % 14]; } }; main(){ vector<int> v1 = {0,1,0,1,1,0,0,1}; Solution ob; print_vector(ob.prisonAfterNDays(v1, 7)); }
[0,1,0,1,1,0,0,1] 7
输出结果
[0,0,1,1,0,0,0,0]