All problems

Problem 626

Sliding Puzzle

Hard · 30 pts · Breadth-First Search, Matrix

Problem

A 2 × 3 board holds the tiles 1 to 5 and one empty square, shown as 0. A move swaps the 0 with a tile directly above, below, left or right of it. The puzzle is solved when the board reads 1 2 3 on the top row and 4 5 0 on the bottom row. Find the minimum number of moves needed to solve the board, or -1 if it cannot be solved. There are only 720 arrangements, so a breadth-first search over board states (stored as 6-character strings) is enough.

Input

Two lines, each with three integers: the top row and the bottom row of the board.

Output

Print the minimum number of moves, or -1.

Constraints

The six values are a permutation of 0, 1, 2, 3, 4, 5

Example input

1 2 3
4 0 5

Example output

1

Explanation

From 1 2 3 / 4 0 5, slide the 5 to the left (swap 0 with 5) to get 1 2 3 / 4 5 0. That is a single move, so the answer is 1.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Shortest Path Visiting All Nodes Next: Reconstruct Itinerary