|
| 1 | +/** |
| 2 | + * 1654. Minimum Jumps to Reach Home |
| 3 | + * https://leetcode.com/problems/minimum-jumps-to-reach-home/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A certain bug's home is on the x-axis at position x. Help them get there from position 0. |
| 7 | + * |
| 8 | + * The bug jumps according to the following rules: |
| 9 | + * - It can jump exactly a positions forward (to the right). |
| 10 | + * - It can jump exactly b positions backward (to the left). |
| 11 | + * - It cannot jump backward twice in a row. |
| 12 | + * - It cannot jump to any forbidden positions. |
| 13 | + * |
| 14 | + * The bug may jump forward beyond its home, but it cannot jump to positions numbered with |
| 15 | + * negative integers. |
| 16 | + * |
| 17 | + * Given an array of integers forbidden, where forbidden[i] means that the bug cannot jump to |
| 18 | + * the position forbidden[i], and integers a, b, and x, return the minimum number of jumps |
| 19 | + * needed for the bug to reach its home. If there is no possible sequence of jumps that lands |
| 20 | + * the bug on position x, return -1. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {number[]} forbidden |
| 25 | + * @param {number} a |
| 26 | + * @param {number} b |
| 27 | + * @param {number} x |
| 28 | + * @return {number} |
| 29 | + */ |
| 30 | +var minimumJumps = function(forbidden, a, b, x) { |
| 31 | + const forbiddenSet = new Set(forbidden); |
| 32 | + const maxPosition = Math.max(x, Math.max(...forbidden)) + a + b; |
| 33 | + const queue = [[0, 0, false]]; |
| 34 | + const visited = new Set([`0,false`]); |
| 35 | + |
| 36 | + while (queue.length) { |
| 37 | + const [position, jumps, isBackward] = queue.shift(); |
| 38 | + |
| 39 | + if (position === x) return jumps; |
| 40 | + |
| 41 | + const forwardPosition = position + a; |
| 42 | + if (forwardPosition <= maxPosition && !forbiddenSet.has(forwardPosition) |
| 43 | + && !visited.has(`${forwardPosition},false`)) { |
| 44 | + queue.push([forwardPosition, jumps + 1, false]); |
| 45 | + visited.add(`${forwardPosition},false`); |
| 46 | + } |
| 47 | + |
| 48 | + if (!isBackward && b > 0) { |
| 49 | + const backwardPosition = position - b; |
| 50 | + if (backwardPosition >= 0 && !forbiddenSet.has(backwardPosition) |
| 51 | + && !visited.has(`${backwardPosition},true`)) { |
| 52 | + queue.push([backwardPosition, jumps + 1, true]); |
| 53 | + visited.add(`${backwardPosition},true`); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return -1; |
| 59 | +}; |
0 commit comments