Skip to the code
cf.
+25 XP

#432 Slide the Tiles Into Place

medium

A loading screen shows a tiny sliding puzzle: a 2 by 3 board with tiles 1 to 5 and one empty slot, written 0. One move slides a tile that is directly above, below, left, or right of the empty slot into it.

The puzzle is solved when the board is [[1, 2, 3], [4, 5, 0]]. Write fewestSlides(board) that returns the fewest moves to solve it, or -1 if it can't be solved.

Example 1

Input: board = [[1,2,3],[4,0,5]]
Output: 1

Slide the 5 left into the empty slot.

Example 2

Input: board = [[1,2,3],[5,4,0]]
Output: -1

Swapping just two tiles is impossible with sliding moves, so this board can never be solved.

Constraints

  • board is 2 rows of 3 numbers.
  • The numbers are 0 to 5, each exactly once.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).