|
| 1 | +/** |
| 2 | + * 756. Pyramid Transition Matrix |
| 3 | + * https://leetcode.com/problems/pyramid-transition-matrix/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are stacking blocks to form a pyramid. Each block has a color, which is represented by |
| 7 | + * a single letter. Each row of blocks contains one less block than the row beneath it and is |
| 8 | + * centered on top. |
| 9 | + * |
| 10 | + * To make the pyramid aesthetically pleasing, there are only specific triangular patterns that |
| 11 | + * are allowed. A triangular pattern consists of a single block stacked on top of two blocks. |
| 12 | + * The patterns are given as a list of three-letter strings allowed, where the first two characters |
| 13 | + * of a pattern represent the left and right bottom blocks respectively, and the third character |
| 14 | + * is the top block. |
| 15 | + * |
| 16 | + * For example, "ABC" represents a triangular pattern with a 'C' block stacked on top of an 'A' |
| 17 | + * (left) and 'B' (right) block. Note that this is different from "BAC" where 'B' is on the left |
| 18 | + * bottom and 'A' is on the right bottom. |
| 19 | + * |
| 20 | + * You start with a bottom row of blocks bottom, given as a single string, that you must use as |
| 21 | + * the base of the pyramid. |
| 22 | + * |
| 23 | + * Given bottom and allowed, return true if you can build the pyramid all the way to the top such |
| 24 | + * that every triangular pattern in the pyramid is in allowed, or false otherwise. |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * @param {string} bottom |
| 29 | + * @param {string[]} allowed |
| 30 | + * @return {boolean} |
| 31 | + */ |
| 32 | +var pyramidTransition = function(bottom, allowed) { |
| 33 | + const transitions = new Map(); |
| 34 | + for (const [left, right, top] of allowed) { |
| 35 | + const key = left + right; |
| 36 | + transitions.set(key, (transitions.get(key) || '') + top); |
| 37 | + } |
| 38 | + |
| 39 | + function canBuild(row, nextRow = '') { |
| 40 | + if (row.length === 1) return true; |
| 41 | + if (nextRow.length === row.length - 1) return canBuild(nextRow); |
| 42 | + |
| 43 | + const pair = row.slice(nextRow.length, nextRow.length + 2); |
| 44 | + const options = transitions.get(pair) || ''; |
| 45 | + |
| 46 | + for (const top of options) { |
| 47 | + if (canBuild(row, nextRow + top)) return true; |
| 48 | + } |
| 49 | + return false; |
| 50 | + } |
| 51 | + |
| 52 | + return canBuild(bottom); |
| 53 | +}; |
0 commit comments