|
| 1 | +/** |
| 2 | + * 773. Sliding Puzzle |
| 3 | + * https://leetcode.com/problems/sliding-puzzle/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by |
| 7 | + * 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it. |
| 8 | + * |
| 9 | + * The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]]. |
| 10 | + * |
| 11 | + * Given the puzzle board board, return the least number of moves required so that the state of the |
| 12 | + * board is solved. If it is impossible for the state of the board to be solved, return -1. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * @param {number[][]} board |
| 17 | + * @return {number} |
| 18 | + */ |
| 19 | +var slidingPuzzle = function(board) { |
| 20 | + const target = '123450'; |
| 21 | + const moves = [ |
| 22 | + [1, 3], [0, 2, 4], [1, 5], |
| 23 | + [0, 4], [1, 3, 5], [2, 4] |
| 24 | + ]; |
| 25 | + |
| 26 | + const start = board.flat().join(''); |
| 27 | + if (start === target) return 0; |
| 28 | + |
| 29 | + const queue = [[start, 0]]; |
| 30 | + const seen = new Set([start]); |
| 31 | + |
| 32 | + while (queue.length) { |
| 33 | + const [state, steps] = queue.shift(); |
| 34 | + const index = state.indexOf('0'); |
| 35 | + |
| 36 | + for (const next of moves[index]) { |
| 37 | + const chars = state.split(''); |
| 38 | + [chars[index], chars[next]] = [chars[next], chars[index]]; |
| 39 | + const nextState = chars.join(''); |
| 40 | + |
| 41 | + if (nextState === target) return steps + 1; |
| 42 | + |
| 43 | + if (!seen.has(nextState)) { |
| 44 | + seen.add(nextState); |
| 45 | + queue.push([nextState, steps + 1]); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return -1; |
| 51 | +}; |
0 commit comments