forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0957.cpp
More file actions
executable file
·43 lines (37 loc) · 791 Bytes
/
LC0957.cpp
File metadata and controls
executable file
·43 lines (37 loc) · 791 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
Problem Statement: https://leetcode.com/problems/prison-cells-after-n-days/
Time: O(n • 2ⁿ)
Space: O(2ⁿ)
*/
class Solution {
public:
vector<int> prisonAfterNDays(vector<int>& cells, int N) {
int b, n = cells.size();
vector<int> states;
while (N--) {
vector<int> nxt(cells.size());
for (int i = 1; i < n - 1; i++)
nxt[i] = (cells[i - 1] == cells[i + 1]);
cells = nxt;
b = convert(cells);
if (!states.empty() && states[0] == b) {
b = states[N % states.size()];
break;
}
states.push_back(b);
}
for (int i = 0; i < n; i++) {
int mask = b >> (n - i - 1);
cells[i] = mask & 1;
}
return cells;
}
int convert(vector<int>& cells) {
int b = 0;
for (int& cell: cells) {
b <<= 1;
b |= cell;
}
return b;
}
};