This page is still under construction.

Parts of this page are still being built. What you see may change.

Hike on a Graph

Interview

Time limit1sMemory limit128 MB

Summary
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 nn. A line containing n=0n = 0 terminates the input; otherwise 1≤n≤501 \le n \le 50.

Next come three integers p1,p2,p3p_1, p_2, p_3 with 1≤pi≤n1 \le p_i \le n, the starting locations of the three pieces.

Then follows the colour matrix: nn rows of nn whitespace-separated lower-case letters. The entry in row ii, column jj is the colour of the edge between locations ii and jj. 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.

Examples1

  1. Example 1

    Input
    3 1 2 3
    r b r
    b b b
    r b r
    2 1 2 2
    y g
    g y
    0
    
    Expected output
    2
    impossible