Traveling Cube
Time limit1sMemory limit128 MB
Simulate a color-coded rolling cube on a grid that must visit six colored squares in a given order while avoiding black squares, and find the minimum number of rolls.
- Level
Medium7 of 10
- Topics
- BFS, Simulation, Graph
- Solved
- No attempts yet
Problem
On a small planet called Bandai, a landing party from the starship Tadamigawa found colorful cubes rolling across flat areas of the surface, which they named beds. A cube appears at some position on a bed, travels for a while, and then disappears. Science officer Lt. Alyssa Ogawa worked out the rule by which a cube travels.
A bed is a rectangular area tiled with equal squares. Exactly one square is red, one green, one blue, one cyan, one magenta, and one yellow; one or more squares are white; and every remaining square is black.
A cube first appears on a white square. Its faces are colored: top red, bottom cyan, north green, south magenta, east blue, west yellow.
At each step the cube rolls over one of its four bottom edges onto the adjacent square. When the cube rolls onto a chromatic square (red, green, blue, cyan, magenta, or yellow), the top face after the roll must have the same color as that square. Rolling onto a white square has no such restriction. The cube must never roll onto a black square.
During the whole trip the cube may visit each chromatic square only once and any white square any number of times, and it may never visit a black square. The cube disappears when it visits the last chromatic square. The order in which the chromatic squares must be visited is known before the trip begins.
Given that order, find the least number of steps for the cube to visit all six chromatic squares in that order.
Input
The input is a sequence of datasets. Each dataset has the form
w d
c(1,1) ... c(w,1)
...
c(1,d) ... c(w,d)
v1v2v3v4v5v6
The first line has two positive integers and separated by a space. The next lines are strings of characters with no spaces. Each character is one of r, g, b, c, m, y, w, k (red, green, blue, cyan, magenta, yellow, white, black) or the sign #. Each of r, g, b, c, m, y and # occurs exactly once in a dataset. The last line is a six-character string , a permutation of "rgbcmy".
is the width (east-west length) and the depth (north-south length) of the bed, measured in squares; neither exceeds . Character is the north-west corner, the north-east, the south-west and the south-east. A letter gives the color of that square; a # marks a white square that is the cube's starting position.
The string gives the order of colors to visit: the cube must visit the squares colored in this order.
A line containing two zeros separated by a space ends the input.
Output
For each dataset, print on its own line the least number of steps, or unreachable if no such trip exists.