leetcode-957. N 天后的牢房

原始思路

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
44
45
46
47
48
49
50
51
52
53
class Solution {
int count = 0;
Map<String, Integer> map = new HashMap<>();
public int[] prisonAfterNDays(int[] cells, int N) {
int[] ans = new int[cells.length];

dfs(cells, N, ans);
int k = N % map.size();
if (k == 0) {
k = map.size();
}


String[] spl = new String[cells.length];
for (Map.Entry<String, Integer> entry: map.entrySet()) {
if (entry.getValue() == k) {
String str = entry.getKey();
str = str.substring(1, str.length()-1).replace(" ","");
spl = str.split(",");
break;
}
}

for (int i = 0; i < cells.length; i++) {
ans[i] = Integer.parseInt(spl[i]);
}
return ans;
}

public void dfs(int[] cells, int N, int[] ans){
if (count >= N) {
return;
}

count++;
ans[0] = 0;
ans[ans.length - 1] = 0;
for (int j = 1; j <= cells.length - 2; j++) {
if (cells[j - 1] == cells[j + 1]) {
ans[j] = 1;
}else {
ans[j] = 0;
}
}

if (map.containsKey(Arrays.toString(ans))) {
return;
}

map.put(Arrays.toString(ans), count);
dfs(ans, N, cells);
}
}