Hike on a Graph
InterviewTime limit1sMemory limit128 MB
Three pieces on a complete edge-colored graph; a piece may move only along an edge whose color matches the edge between the other two, and we want the fewest moves to gather all three on one vertex.
- Level
Medium6 of 10
- Topics
- BFS, Graph, Shortest path, Simulation
- Solved
- No attempts yet
Problem
Hike on a Graph is played on a board showing an undirected graph. The graph is complete and has a loop at every vertex: between any two locations — and from a location to itself — there is exactly one edge, and every edge is coloured.
There are three players, each with one piece. At the start the three pieces sit on fixed locations. On a turn a player moves their own piece along an edge to another location, subject to one rule: the piece may only travel along edges whose colour matches the colour of the edge joining the two opponents' pieces.
A one-person variant appeared later: a single person moves all three pieces, one at a time and in any order. The goal is to gather all three pieces onto the same location using as few moves as possible.
Given a board and the starting positions, determine the smallest number of moves needed to bring all three pieces onto one location.
Input
The input contains several test cases. Each test case begins with an integer . A line containing terminates the input; otherwise .
Next come three integers with , the starting locations of the three pieces.
Then follows the colour matrix: rows of whitespace-separated lower-case letters. The entry in row , column is the colour of the edge between locations and . Because the graph is undirected, the matrix is symmetric.
Output
For each test case, print a single line: the minimum number of moves needed to bring all three pieces onto the same location, or the word impossible if it cannot be done for the given board and starting positions.