Under construction

Still being built. Things may change

Moving a Log

Time limit2sMemory limit128 MB

Summary
Find the minimum number of moves and 90-degree rotations to slide a 3-cell log from a start position to a goal position on a grid with obstacles.
Level

Medium6 of 10

Topics
BFS, Simulation, Implementation
Solved
No attempts yet

Problem

Logging is done on a square field. The field is described with characters: 0 is an empty cell, 1 is an uncut tree, B is the initial position of the log, and E is the final position where the log must be moved.

A field may look like this.

B 0 0 1 1
B 0 0 0 0
B 0 0 0 0
1 1 0 0 0
E E E 0 0

The log always has length 3, and its three cells are consecutive in one row or one column. The initial three cells are marked with B, and the target three cells are marked with E. The log can use only the following five basic actions.

CodeMeaning
UMove the log one cell up.
DMove the log one cell down.
LMove the log one cell left.
RMove the log one cell right.
TRotate it 90 degrees around its center cell.

When the log moves up, down, left, or right, all three cells occupied after the move must remain inside the field, and none of them may contain 1. Each move shifts the log by exactly one cell, and the log must always stay on a single row or a single column.

A rotation is performed only around the middle cell of the log. Because the length is 3, that center cell always exists. To rotate, the entire 3 x 3 square around the center cell must be inside the field, and none of those 9 cells may contain 1. In the diagrams below, every cell marked with a question mark must also be empty.

Space needed to rotate a horizontal log:

0 0 0 0 0
0 ? ? ? 0
0 B B B 0
0 ? ? ? 0
0 0 0 0 0

Space needed to rotate a vertical log:

0 0 0 0 0
0 ? B ? 0
0 ? B ? 0
0 ? B ? 0
0 0 0 0 0

Find the minimum number of basic actions needed to move the log from its initial position to its final position.

Input

The first line contains N, the side length of the square field. (4 <= N <= 50)

The next N lines describe the field. Each line is a string of length N with no spaces between characters. Each character is one of 0, 1, B, and E.

There are exactly three B cells for the initial position and exactly three E cells for the final position. Each group of three cells is consecutive in one row or one column.

Output

Print the minimum number of actions needed to move the log from its initial position to its final position.

If it is impossible, print 0.

Examples2

  1. Example 1

    Input
    5
    B0011
    B0000
    B0000
    11000
    EEE00
    
    Expected output
    9
  2. Example 2

    Input
    4
    B000
    B01E
    B00E
    000E
    
    Expected output
    0