All problems
1074HardArrayDynamic ProgrammingBacktrackingBreadth-First SearchMemoizationMatrixHeuristic SearchBidirectional SearchA* Search

Fewest Slides to Order the Tray

Tracked in this browser only
Write code

Trains the technique from

LeetCode 773Sliding Puzzle

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A tray holds five marked tiles and one gap, laid out as tray, two rows of three. The tiles carry the marks 1 through 5 and the gap is written 0.

One slide moves a tile that sits directly beside the gap, edgewise, into the gap; the tile and the gap change places.

Return the fewest slides needed to reach the layout with 1, 2, 3 along the top row and 4, 5 then the gap along the bottom, or -1 when no number of slides can reach it.

Examples

Example 1

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

The tray is already in the wanted layout, so nothing needs sliding.

Example 2

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

Sliding the 4 up, then the 5 left, then the 3 left brings the tray into order in three slides.

Example 3

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

Only the 1 and the 2 are out of order, with everything else already in place. A slide never changes the layout's parity, so this layout can never reach the wanted one.

Constraints

  • tray.length == 2
  • tray[i].length == 3
  • 0 <= tray[i][j] <= 5
  • No two cells of the tray hold the same mark.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def sliding_puzzle(tray: list[list[int]]) -> int:
Java
public int slidingPuzzle(int[][] tray)
September 7
Apply