Prison Cells After N Days in C++

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 
using namespace std;
void print_vector(vector v){
   cout  prisonAfterNDays(vector& cells, int N) {
      map  > m;
      if(N == 0) return cells;
      set  > visited;
      visited.insert(cells);
      for(int i = 1; i temp(8);
         for(int j = 1; j  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]
Updated on: 2020-04-30T13:33:33+05:30

521 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements