Moveable Maze
Time limit1sMemory limit128 MB
Each turn lets you rotate one grid square by 90 degrees and then take one step along matching lines, and you must minimize turns from a start cell to a goal cell.
- Level
Hard8 of 10
- Topics
- BFS, Graph, Simulation, Bit manipulation
- Solved
- No attempts yet
Problem
You are playing a puzzle game on a grid with rows and columns. Each square has a black dot at its centre, and black lines may extend from that dot toward some of its north, east, south, and west neighbours (possibly none of them, possibly all four).
Your piece starts at the centre of the square in row , column , and you want to move it to the centre of the square in row , column , using as few turns as possible.
A turn has two parts, and either part may be skipped:
- Rotation: you may pick any one square of the grid and rotate it 90 degrees, clockwise or counterclockwise. All of that square's lines rotate together.
- Movement: you may move your piece from the centre of its current square to the centre of a neighbouring square, as long as the piece never leaves the black lines. Concretely, you may move from square to a neighbouring square only if has a line pointing toward and has a line pointing back toward .
Print the minimum number of turns needed to move the piece from to . It is guaranteed that the destination is reachable.
Input
The input contains several test cases.
The first line of each test case contains two integers and ().
The second line contains four integers , , , ( and ): the starting row and column, then the destination row and column.
Each of the next lines describes one row of the grid, from north (top) to south (bottom). Every such line contains exactly space-separated tokens describing that row's squares from west (left) to east (right). Each token is one of:
- the single character
x, meaning the square has no line to any neighbour; or - a string made of some of the characters
N,E,S,W(each appearing at most once), whereN,E,S,Wmean the square has a line toward its north, east, south, or west neighbour respectively.
It is guaranteed that the piece can be moved from to .
The input ends with a line containing 0 0, which must not be processed as a test case.
Output
For each test case, print a single line containing one integer: the minimum number of turns required to move the piece from to .
Hint
Rotating a square affects only that square, but you may rotate any square on the board (not only the one your piece is on), so you can prepare distant squares in advance. Because rotation and movement can happen in the same turn, aligning a path and walking along it can overlap.
For a board where the piece starts in row 1, column 1 and must reach row 4, column 1, one optimal sequence of 5 turns is:
- Rotate square clockwise, then step to .
- Rotate square counterclockwise, then step to .
- Rotate square counterclockwise, then step to .
- Rotate square clockwise, then step to .
- Rotate square clockwise, then step to .