Prison Cells After N Days in C++

C++Server Side ProgrammingProgramming

Suppose there are 8 prison cells in a row, and in each cell there is a prisoner or that is empty. In each day, whether the cell is occupied or vacant changes according to the following rules −

  • If one cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.

  • Otherwise, it becomes empty.

We will describe the current state of the prison in the following way: cells[i] will be 1 if the i-th cell is occupied, else cells[i] will be 0.

So we have the initial state of the prison, then return the state of the prison after N days.

So if the input is like: [0,1,0,1,1,0,0,1], and N = 7, then the output will be [0,0,1,1,0,0,0,0]. So this is because of the following. For seven days −

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]

To solve this, we will follow these steps −

  • Create a map m, and create one set called visited.

  • if N is 0, then return cells

  • insert cells into visited set

  • for i in range 1 to 14

    • create an array called temp of size 8

    • for j in range 1 to 6

      • if cells[j – 1] XOR cells[j + 1] = 0, then temp[j] := 1

    • cells := temp

    • m[i] := temp

    • insert temp into visited

  • if N is divisible by 14, then return m[14], otherwise m[N mod 14]

Let us see the following implementation to get better understanding −

Example

 Live Demo

#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));
}

Input

[0,1,0,1,1,0,0,1]
7

Output

[0,0,1,1,0,0,0,0]
raja
Published on 10-Apr-2020 13:51:53
Advertisements