|
4 | 4 | * @return {boolean}
|
5 | 5 | */
|
6 | 6 | const pyramidTransition = function (bottom, allowed) {
|
7 |
| - const map = new Map() |
8 |
| - allowed.map((item) => { |
9 |
| - const t = map.get(item[0] + item[1]) || new Array() |
10 |
| - t.push(item[2]) |
11 |
| - map.set(item[0] + item[1], t) |
12 |
| - }) |
13 |
| - const memo = new Map() |
14 |
| - const solve = function (cur, ind, next) { |
15 |
| - if (memo.has(cur)) return memo.get(cur) |
16 |
| - if (cur.length === 1) return true |
17 |
| - if (ind >= cur.length - 1) { |
18 |
| - const res = solve(next, 0, '') |
19 |
| - memo.set(next, res) |
20 |
| - return res |
21 |
| - } |
22 |
| - if (!map.has(cur.slice(ind, ind + 2))) { |
23 |
| - memo.set(cur, false) |
24 |
| - return false |
25 |
| - } |
26 |
| - for (let char of map.get(cur.slice(ind, ind + 2))) { |
27 |
| - if (solve(cur, ind + 1, next + char)) return true |
28 |
| - } |
29 |
| - return false |
| 7 | + const m = new Map() |
| 8 | + for (let e of allowed) { |
| 9 | + const p = e.slice(0, 2) |
| 10 | + if (!m.has(p)) m.set(p, new Set()) |
| 11 | + m.get(p).add(e[2]) |
30 | 12 | }
|
31 |
| - return solve(bottom, 0, '') |
| 13 | + return dfs(bottom, '', m, 0) |
32 | 14 | }
|
| 15 | + |
| 16 | +function dfs(row, next, m, i) { |
| 17 | + if (row.length === 1) return true |
| 18 | + if (next.length + 1 === row.length) return dfs(next, '', m, 0) |
| 19 | + for (let c of m.get(row.slice(i, i + 2)) || new Set()) |
| 20 | + if (dfs(row, next + c, m, i + 1)) return true |
| 21 | + return false |
| 22 | +} |
| 23 | + |
0 commit comments