1 #include<iostream>
2 #include<string.h>
3 #include<queue>
4 #define PROCESS a=min3(next.p1,next.p2,next.p3);c=max3(next.p1,next.p2,next.p3);b=next.p1+next.p2+next.p3-a-c;if( hash[a][b][c] ) continue;hash[a][b][c]=true;next.dist=cur.dist+1;if( a==c ) return next.dist;Q.push(next);
5 using namespace std;
6
7 char graph[51][51];
8 bool hash[51][51][51];
9 typedef struct
10 {
11 int p1,p2,p3,dist;
12 }node;
13 node sn;
14 int n;
15
16 int max3(int a,int b,int c)
17 {
18 return (a<b?a:b)<c?(a<b?a:b):c;
19 }
20
21 int min3(int a,int b,int c)
22 {
23 return (a>b?a:b)>c?(a>b?a:b):c;
24 }
25
26 int bfs(void)
27 {
28 queue<node> Q;
29 int a,b,c;
30
31 if( sn.p1==sn.p2 && sn.p2==sn.p3 ) return 0;
32 memset(hash,false,sizeof(hash));
33 sn.dist=0;
34 a=min3(sn.p1,sn.p2,sn.p3);
35 c=max3(sn.p1,sn.p2,sn.p3);
36 b=sn.p1+sn.p2+sn.p3-a-c;
37 hash[a][b][c]=true;
38 Q.push(sn);
39 while( !Q.empty() )
40 {
41 node cur=Q.front();
42
43 Q.pop();
44 for(int i=1;i<=n;i++)
45 {
46 node next=cur;
47
48 if( graph[next.p1][i] != graph[next.p2][next.p3] ) continue;
49 next.p1=i;
50 PROCESS
51 }
52 for(int i=1;i<=n;i++)
53 {
54 node next=cur;
55
56 if( graph[next.p2][i] != graph[next.p1][next.p3] ) continue;
57 next.p2=i;
58 PROCESS
59 }
60 for(int i=1;i<=n;i++)
61 {
62 node next=cur;
63
64 if( graph[next.p3][i] != graph[next.p1][next.p2] ) continue;
65 next.p3=i;
66 PROCESS
67 }
68 }
69 return -1;
70 }
71
72 int main()
73 {
74 int ans;
75
76 while( cin>>n ,n )
77 {
78 cin>>sn.p1>>sn.p2>>sn.p3;
79 for(int i=1;i<=n;i++)
80 for(int j=1;j<=n;j++)
81 cin>>graph[i][j];
82 ans=bfs();
83 if( ans!=-1 ) cout<<ans<<endl;
84 else cout<<"impossible"<<endl;
85 }
86 return 0;
87 }
88 /*
89 简单bfs
90 1.题目描述看了半天
91 2.单字符输入WA了一次,改成cin>>
92 3.hash时将p1,p2,p3排序,应该是个剪枝了
93 */