|
| 1 | +/** |
| 2 | + * 1345. Jump Game IV |
| 3 | + * https://leetcode.com/problems/jump-game-iv/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given an array of integers arr, you are initially positioned at the first index of the array. |
| 7 | + * |
| 8 | + * In one step you can jump from index i to index: |
| 9 | + * - i + 1 where: i + 1 < arr.length. |
| 10 | + * - i - 1 where: i - 1 >= 0. |
| 11 | + * - j where: arr[i] == arr[j] and i != j. |
| 12 | + * |
| 13 | + * Return the minimum number of steps to reach the last index of the array. |
| 14 | + * |
| 15 | + * Notice that you can not jump outside of the array at any time. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number[]} arr |
| 20 | + * @return {number} |
| 21 | + */ |
| 22 | +var minJumps = function(arr) { |
| 23 | + const n = arr.length; |
| 24 | + if (n <= 1) return 0; |
| 25 | + |
| 26 | + const valueToIndices = new Map(); |
| 27 | + for (let i = 0; i < n; i++) { |
| 28 | + if (!valueToIndices.has(arr[i])) { |
| 29 | + valueToIndices.set(arr[i], []); |
| 30 | + } |
| 31 | + valueToIndices.get(arr[i]).push(i); |
| 32 | + } |
| 33 | + |
| 34 | + const visited = new Set([0]); |
| 35 | + let queue = [0]; |
| 36 | + let result = 0; |
| 37 | + |
| 38 | + while (queue.length) { |
| 39 | + const nextQueue = []; |
| 40 | + |
| 41 | + for (const current of queue) { |
| 42 | + if (current === n - 1) return result; |
| 43 | + |
| 44 | + if (current + 1 < n && !visited.has(current + 1)) { |
| 45 | + visited.add(current + 1); |
| 46 | + nextQueue.push(current + 1); |
| 47 | + } |
| 48 | + |
| 49 | + if (current - 1 >= 0 && !visited.has(current - 1)) { |
| 50 | + visited.add(current - 1); |
| 51 | + nextQueue.push(current - 1); |
| 52 | + } |
| 53 | + |
| 54 | + for (const next of valueToIndices.get(arr[current]) || []) { |
| 55 | + if (!visited.has(next)) { |
| 56 | + visited.add(next); |
| 57 | + nextQueue.push(next); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + valueToIndices.delete(arr[current]); |
| 62 | + } |
| 63 | + |
| 64 | + queue = nextQueue; |
| 65 | + result++; |
| 66 | + } |
| 67 | + |
| 68 | + return result; |
| 69 | +}; |
0 commit comments