-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0756-pyramid-transition-matrix.js
More file actions
52 lines (45 loc) · 1.28 KB
/
0756-pyramid-transition-matrix.js
File metadata and controls
52 lines (45 loc) · 1.28 KB
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
/**
* Pyramid Transition Matrix
* Time Complexity: O(A + N * K^N)
* Space Complexity: O(K^3 + N^2)
*/
var pyramidTransition = function (bottom, allowed) {
const validPatternsMap = new Map();
for (const patternEntry of allowed) {
const baseBlocks = patternEntry.substring(0, 2);
const topBlock = patternEntry.charAt(2);
validPatternsMap.set(
baseBlocks,
(validPatternsMap.get(baseBlocks) || "") + topBlock,
);
}
function recursivePyramidCheck(currentRowFormation, currentNextRow = "") {
if (currentRowFormation.length === 1) {
return true;
}
if (currentNextRow.length === currentRowFormation.length - 1) {
return recursivePyramidCheck(currentNextRow);
}
const currentPairIndex = currentNextRow.length;
const subSegment = currentRowFormation.substring(
currentPairIndex,
currentPairIndex + 2,
);
const nextLevelOptions = validPatternsMap.get(subSegment);
if (!nextLevelOptions) {
return false;
}
for (const candidateTopBlock of nextLevelOptions) {
if (
recursivePyramidCheck(
currentRowFormation,
currentNextRow + candidateTopBlock,
)
) {
return true;
}
}
return false;
}
return recursivePyramidCheck(bottom);
};