#include <iostream>
#include <queue>
using namespace std;
typedef pair<int, int> P;
typedef long long ll;
int width, height, count, startH[10], startW[10], endH[10], endW[10], ans[1007][1007], dh[5] = {0, 1, 0, -1, 0}, dw[5] = {0, 0, 1, 0, -1}, inf = 0x3f3f3f3f;
char field[1007][1007], tag[10] = {'S', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
void setStart(int h, int w, char c)
{
for (int i = 0; i <= count; i++)
{
if (c != tag[i])
{
continue;
}
startH[i] = h, startW[i] = w;
if (i == 0)
{
continue;
}
endH[i - 1] = h, endW[i - 1] = w;
}
}
void input()
{
for (int h = 1; h <= height; h++)
{
scanf("\n");
for (int w = 1; w <= width; w++)
{
scanf("%c", &field[h][w]);
setStart(h, w, field[h][w]);
}
}
}
bool isValid(int h, int w)
{
return h >= 1 && h <= height && w >= 1 && w <= width && field[h][w] != 'X';
}
void setAnsToInf()
{
for (int h = 1; h <= height; h++)
{
for (int w = 1; w <= width; w++)
{
ans[h][w] = inf;
}
}
}
int bfs(int i)
{
setAnsToInf();
ans[startH[i]][startW[i]] = 0;
queue<P> que;
que.push(P(startH[i], startW[i]));
while (!que.empty())
{
P p = que.front();
que.pop();
for (int i = 1; i <= 4; i++)
{
if (!isValid(p.first + dh[i], p.second + dw[i]))
{
continue;
}
int newH = p.first + dh[i], newW = p.second + dw[i];
if (ans[p.first][p.second] + 1 >= ans[newH][newW])
{
continue;
}
ans[newH][newW] = ans[p.first][p.second] + 1;
que.push(P(newH, newW));
}
}
return ans[endH[i]][endW[i]];
}
int main()
{
scanf("%d%d%d", &height, &width, &count);
input();
ll result = 0LL;
for (int i = 0; i < count; i++)
{
result += bfs(i);
}
printf("%lld\n", result);
return 0;
}