|
| 1 | +/** |
| 2 | + * 514. Freedom Trail |
| 3 | + * https://leetcode.com/problems/freedom-trail/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial |
| 7 | + * called the "Freedom Trail Ring" and use the dial to spell a specific keyword to open the door. |
| 8 | + * |
| 9 | + * Given a string ring that represents the code engraved on the outer ring and another string key |
| 10 | + * that represents the keyword that needs to be spelled, return the minimum number of steps to spell |
| 11 | + * all the characters in the keyword. |
| 12 | + * |
| 13 | + * Initially, the first character of the ring is aligned at the "12:00" direction. You should spell |
| 14 | + * all the characters in key one by one by rotating ring clockwise or anticlockwise to make each |
| 15 | + * character of the string key aligned at the "12:00" direction and then by pressing the center |
| 16 | + * button. |
| 17 | + * |
| 18 | + * At the stage of rotating the ring to spell the key character key[i]: |
| 19 | + * - You can rotate the ring clockwise or anticlockwise by one place, which counts as one step. |
| 20 | + * The final purpose of the rotation is to align one of ring's characters at the "12:00" |
| 21 | + * direction, where this character must equal key[i]. |
| 22 | + * - If the character key[i] has been aligned at the "12:00" direction, press the center button |
| 23 | + * to spell, which also counts as one step. After the pressing, you could begin to spell the |
| 24 | + * next character in the key (next stage). Otherwise, you have finished all the spelling. |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * @param {string} ring |
| 29 | + * @param {string} key |
| 30 | + * @return {number} |
| 31 | + */ |
| 32 | +var findRotateSteps = function(ring, key) { |
| 33 | + const map = new Map(); |
| 34 | + return dp(0, 0); |
| 35 | + |
| 36 | + function dp(ringIndex, keyIndex) { |
| 37 | + if (keyIndex === key.length) return 0; |
| 38 | + const state = `${ringIndex},${keyIndex}`; |
| 39 | + if (map.has(state)) return map.get(state); |
| 40 | + let minSteps = Infinity; |
| 41 | + for (let i = 0; i < ring.length; i++) { |
| 42 | + if (ring[i] === key[keyIndex]) { |
| 43 | + const distance = Math.abs(i - ringIndex); |
| 44 | + const steps = Math.min(distance, ring.length - distance); |
| 45 | + minSteps = Math.min(minSteps, steps + 1 + dp(i, keyIndex + 1)); |
| 46 | + } |
| 47 | + } |
| 48 | + map.set(state, minSteps); |
| 49 | + return minSteps; |
| 50 | + } |
| 51 | +}; |
0 commit comments