#include <cstdio>
#include <queue>
#include <map>
using namespace std;
typedef pair<pair<int, int>, pair<int, int> > MP;
#define mp(a,b) make_pair(a,b)
#define mf(a,b,c,d) mp(mp(a,b),mp(c,d))
int N, M, R, L;
char arr[11][11];
int robot[4];
int goal;
map<MP,int> seen;
struct Pos{
int y, x;
void append(int site){
y = site / M;
x = site % M;
}
};
void Push(int num, int next, int moves, queue<MP> &q){
MP p;
if (num == 0) p = mf(next, q.front().first.second, q.front().second.first, q.front().second.second);
else if (num == 1) p = mf(q.front().first.first, next, q.front().second.first, q.front().second.second);
else if (num == 2) p = mf(q.front().first.first, q.front().first.second, next, q.front().second.second);
else if (num == 3) p = mf(q.front().first.first, q.front().first.second, q.front().second.first, next);
if (seen.find(p) == seen.end()) {
q.push(p);
seen[p] = moves;
}
}
int bfs(){
int ans = 0;
int dy[] = { -1, 0, 0, 1 }, dx[] = { 0, 1, -1, 0 };
queue<MP> q; //좌표, 로봇번호
q.push(mf(robot[0],robot[1],robot[2],robot[3]));
while (!q.empty()){
int sz = q.size();
for (int s = 0; s < sz; s++){
Pos curr[4];
curr[0].append(q.front().first.first), curr[1].append(q.front().first.second),
curr[2].append(q.front().second.first), curr[3].append(q.front().second.second);
if (curr[0].y * M + curr[0].x == goal) return ans;
for (int r = 0; r < R; r++){
int y = curr[r].y, x = curr[r].x;
for (int i = 0; i < 4; i++){
int ny = y, nx = x;
while (1){
bool f = false;
ny += dy[i], nx += dx[i];
if (ny < 0 || ny >= N || nx < 0 || nx >= M || arr[ny][nx] == 'W') break;
for (int rr = 0; rr < R; rr++){
if (rr == r) continue;
if (ny == curr[rr].y && nx == curr[rr].x){ f = true; break; }
}
if (f) break;
}
ny -= dy[i], nx -= dx[i];
if (ny == y && nx == x) continue;
int next = ny*M + nx;
Push(r, next, ans, q);
}
}
q.pop();
}
ans++;
if (ans > L) return -1;
}
return -1;
}
int main(){
scanf("%d%d%d%d", &R, &M, &N, &L);
for (int n = 0; n < N; n++)
for (int m = 0; m < M; m++){
scanf(" %1c", &arr[n][m]);
if (arr[n][m] == 'X'){
goal = n*M + m;
arr[n][m] = '.';
}
for (int r = 1; r <= R; r++){
if (arr[n][m] - '0' == r){
robot[r - 1] = n*M + m;
arr[n][m] = '.';
}
}
}
int ans = bfs();
if (ans == -1) printf("NO SOLUTION\n");
else printf("%d\n", ans);
return 0;
}