//* Problem  : H - Hike on a Graph
//* Contest  : acm.tju.edu.cn
//* Origin   : University of Ulm Local Contest 2000
//* Type     : Solution
//* Date     : 2008.06.07
//* Author   : alt
//* Language : C++
//* Compiler : Microsoft Visual C++ 8.0

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>

#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include <string>
#include <iostream>
using namespace std;
#define int64 long long
#define INF 1000000000
#define EPS 1E-8

#define ALL(a) a.begin(), a.end()
#define PB(a, v) a.push_back(v)
#define MP(a,b) make_pair(a, b)
#define FOR(i, n) for (int i = 0; i < (int)(n); i++)
#define FORO(i, obj) for (int i = 0; i < (int)(obj.size); i++)

int n, res;

int dp[64][64][64], p1, p2, p3;

char a[64][64];

queue <pair< int, pair<int, int> > > q;

int main()
{
#ifdef _DEBUG
	freopen("1166.in", "r", stdin);
#endif
	while (scanf("%d", &n) == 1 && n)
	{
		memset(dp, 0, sizeof(dp));
		scanf("%d%d%d", &p1, &p2, &p3);
		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= n; j++)
			{
				char s[10]; scanf("%s", s);
				a[i][j] = s[0];
			}
		q.push(MP(p1, MP(p2, p3))); dp[p1][p2][p3] = 1; 
		while (!q.empty())
		{
			pair< int, pair<int, int> > p = q.front(); q.pop();
			p1 = p.first; p2 = p.second.first; p3 = p.second.second;
			for (int v = 1; v <= n; v++)
			{
				int d = dp[p1][p2][p3];
				if (a[v][p1] == a[p2][p3])
					if (!dp[v][p2][p3])
					{
						q.push(MP(v, MP(p2, p3))); dp[v][p2][p3] = d + 1;
					}
				if (a[v][p2] == a[p1][p3])
					if (!dp[p1][v][p3])
					{
						q.push(MP(p1, MP(v, p3))); dp[p1][v][p3] = d + 1;
					}
				if (a[v][p3] == a[p2][p1])
					if (!dp[p1][p2][v])
					{
						q.push(MP(p1, MP(p2, v))); dp[p1][p2][v] = d + 1;
					}


			}
		}
		res = INF;
		for (int i = 1; i <= n; i++)
			if (dp[i][i][i])
				res = min(res, dp[i][i][i]);
		if (res == INF) printf("impossible\n");
		else printf("%d\n", res - 1);
	}
	return 0;
}
