Sliding Block Puzzle

Time limit5sMemory limit128 MB

Summary
Find the minimum number of moves to slide a 2x2 king piece and 1x1 pawns through two open cells until the king reaches the frame's top-left corner.
Level

Hard8 of 10

Topics
BFS, Graph, Implementation
Solved
No attempts yet

Problem

In sliding block puzzles, we repeatedly slide pieces (blocks) into open spaces within a frame to reach a goal arrangement of the pieces.

A puzzle creator has designed a new puzzle by combining the ideas of sliding block puzzles and mazes. The puzzle is played in a rectangular frame divided into unit squares. Some squares are pre-occupied by obstacles. Inside the frame there are several pieces: exactly one 2×22 \times 2 king piece and some number of 1×11 \times 1 pawn pieces. Exactly two 1×11 \times 1 squares are left open. If a pawn piece is adjacent to an open square, we can slide that piece into it. If an entire edge of the king piece is adjacent to two open squares, we can slide the king piece one cell in that direction. Obstacles cannot be moved. Starting from a given initial placement, the goal is to move the king piece to the upper-left corner of the frame.

Your task is to write a program that computes the minimum number of moves needed to solve the puzzle from a given placement of pieces. Here, one move means sliding either the king piece or a single pawn piece to an adjacent position.

Input

The input is a sequence of datasets. The first line of a dataset contains two integers HH and WW separated by a space, where HH and WW are the height and the width of the frame. Each of the following HH lines contains WW characters describing the initial placement of the pieces. In those lines, X, o, *, and . denote a part of the king piece, a pawn piece, an obstacle, and an open square, respectively. No other characters appear. You may assume that 3≤H≤503 \le H \le 50 and 3≤W≤503 \le W \le 50.

A line containing two zeros separated by a space marks the end of the input.

Output

For each dataset, output on its own line the minimum number of moves required to move the king piece to the upper-left corner. If it is impossible, output -1.

Examples1

  1. Example 1

    Input
    3 3
    oo.
    oXX
    .XX
    3 3
    XXo
    XX.
    o.o
    3 5
    .o*XX
    oooXX
    oooo.
    7 12
    oooooooooooo
    ooooo*****oo
    oooooo****oo
    o**ooo***ooo
    o***ooooo..o
    o**ooooooXXo
    ooooo****XXo
    5 30
    oooooooooooooooooooooooooooooo
    oooooooooooooooooooooooooooooo
    o***************************oo
    XX.ooooooooooooooooooooooooooo
    XX.ooooooooooooooooooooooooooo
    0 0
    
    Expected output
    11
    0
    -1
    382
    6807