#include <iostream>
#include <queue>
#define N 1002
using namespace std;
int bfs(pair<int, int>, pair<int, int>);
int h, w, d[N][N];
string str[N];
int main() {
  int n, i, j, sum;
  pair<int, int> P[10];
  cin >> h >> w >> n;
  for (i = 0; i <= w + 1; i++)
    str[0] += 'X', str[h + 1] += 'X';
  for (i = 1; i <= h; i++)
    cin >> str[i], str[i] = 'X' + str[i] + 'X';
  for (i = 1; i <= h; i++) {
    for (j = 1; j <= w; j++) {
      if (str[i][j] == 'S')
        P[0].first = i, P[0].second = j;
      if ('1' <= str[i][j] && str[i][j] <= '9') {
        P[str[i][j] - '0'].first = i;
        P[str[i][j] - '0'].second = j;
      }
    }
  }
  sum = bfs(P[0], P[1]);
  for (i = 1; i < n; i++)
    sum += bfs(P[i], P[i + 1]);
  cout << sum << endl;
}
int bfs(pair<int, int> s, pair<int, int> g) {
  int i, j, ret;
  pair<int, int> t;
  pair<int, int> u;
  queue<pair<int, int>> Q;
  for (i = 1; i <= h; i++) {
    for (j = 1; j <= w; j++) {
      d[i][j] = -1;
    }
  }
  Q.push(s);
  d[s.first][s.second] = 0;
  while (Q.empty() != 1) {
    u = Q.front();
    if (str[u.first][u.second] == str[g.first][g.second]) {
      ret = d[u.first][u.second];
      break;
    }
    Q.pop();
    for (i = 1; i <= h; i++) {
      for (j = 1; j <= w; j++) {
        if (u.first == i && u.second == j) {
          if (d[i][j - 1] == -1 && str[i][j - 1] != 'X') {
            d[i][j - 1] = d[u.first][u.second] + 1;
            t.first = i;
            t.second = j - 1;
            Q.push(t);
          }
          if (d[i][j + 1] == -1 && str[i][j + 1] != 'X') {
            d[i][j + 1] = d[u.first][u.second] + 1;
            t.first = i;
            t.second = j + 1;
            Q.push(t);
          }
          if (d[i - 1][j] == -1 && str[i - 1][j] != 'X') {
            d[i - 1][j] = d[u.first][u.second] + 1;
            t.first = i - 1;
            t.second = j;
            Q.push(t);
          }
          if (d[i + 1][j] == -1 && str[i + 1][j] != 'X') {
            d[i + 1][j] = d[u.first][u.second] + 1;
            t.first = i + 1;
            t.second = j;
            Q.push(t);
          }
        }
      }
    }
  }
  return ret;
}

#include <iostream>
#include <queue>
#define N 1002
using namespace std;
int bfs(pair<int, int>, pair<int, int>);
int h, w, d[N][N];
string str[N];
int main() {
  int n, i, j, sum;
  pair<int, int> P[10];
  cin >> h >> w >> n;
  for (i = 0; i <= w + 1; i++)
    str[0] += 'X', str[h + 1] += 'X';
  for (i = 1; i <= h; i++)
    cin >> str[i], str[i] = 'X' + str[i] + 'X';
  for (i = 1; i <= h; i++) {
    for (j = 1; j <= w; j++) {
      if (str[i][j] == 'S')
        P[0].first = i, P[0].second = j;
      if ('1' <= str[i][j] && str[i][j] <= '9') {
        P[str[i][j] - '0'].first = i;
        P[str[i][j] - '0'].second = j;
      }
    }
  }
  sum = bfs(P[0], P[1]);
  for (i = 1; i < n; i++)
    sum += bfs(P[i], P[i + 1]);
  cout << sum << endl;
}
int bfs(pair<int, int> s, pair<int, int> g) {
  int i, j, ret;
  pair<int, int> t;
  pair<int, int> u;
  queue<pair<int, int>> Q;
  for (i = 1; i <= h; i++) {
    for (j = 1; j <= w; j++) {
      d[i][j] = -1;
    }
  }
  Q.push(s);
  d[s.first][s.second] = 0;
  while (Q.empty() != 1) {
    u = Q.front();
    if (str[u.first][u.second] == str[g.first][g.second]) {
      ret = d[u.first][u.second];
      break;
    }
    Q.pop();
    if (d[u.first][u.second - 1] == -1 && str[u.first][u.second - 1] != 'X') {
      d[u.first][u.second - 1] = d[u.first][u.second] + 1;
      t.first = u.first;
      t.second = u.second - 1;
      Q.push(t);
    }
    if (d[u.first][u.second + 1] == -1 && str[u.first][u.second + 1] != 'X') {
      d[u.first][u.second + 1] = d[u.first][u.second] + 1;
      t.first = u.first;
      t.second = u.second + 1;
      Q.push(t);
    }
    if (d[u.first - 1][u.second] == -1 && str[u.first - 1][u.second] != 'X') {
      d[u.first - 1][u.second] = d[u.first][u.second] + 1;
      t.first = u.first - 1;
      t.second = u.second;
      Q.push(t);
    }
    if (d[u.first + 1][u.second] == -1 && str[u.first + 1][u.second] != 'X') {
      d[u.first + 1][u.second] = d[u.first][u.second] + 1;
      t.first = u.first + 1;
      t.second = u.second;
      Q.push(t);
    }
  }
  return ret;
}


#include <iostream>
#include <queue>

#define INF 1e9
#define MAX_H 1000
#define MAX_W 1000

using namespace std;

struct Cood {
  int x, y;
};

int N;
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};

char field[MAX_H][MAX_W + 1];
int d[MAX_H][MAX_W + 1];
queue<Cood> q;
int h, w, n;
int total_time = 0;

void init_bfs() {
  queue<Cood> new_q;
  swap(q, new_q);
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      d[i][j] = INF;
    }
  }
}
/* current position (y, x) with current power 'current' & last cheeese target is
 * 'last' */
int bfs(int sy, int sx, int target, int last) {
  init_bfs();
  int next_y, next_x;
  q.push(Cood{sx, sy});
  d[sy][sx] = 0;

  while (q.size()) {
    Cood current = q.front();
    q.pop();
    if (field[current.y][current.x] == '0' + target) {
      total_time += d[current.y][current.x];
      if (target == last) {
        return total_time;
      } else {
        return bfs(current.y, current.x, target + 1, last);
      }
    }

    for (int i = 0; i < 4; ++i) {
      next_y = current.y + dy[i];
      next_x = current.x + dx[i];
      if (0 <= next_y && next_y < h && 0 <= next_x && next_x < w &&
          field[next_y][next_x] != 'X' && d[next_y][next_x] == INF) {
        q.push(Cood{next_x, next_y});
        d[next_y][next_x] = d[current.y][current.x] + 1;
      }
    }
  }
}

int main() {
  // freopen("0558.in", "r", stdin);

  while (cin >> h >> w >> n, h | w) {
    int sx, sy;
    for (int i = 0; i < h; ++i) {
      for (int j = 0; j < w; ++j) {
        cin >> field[i][j];
        if (field[i][j] == 'S') {
          sy = i, sx = j;
        }
      }
    }
    total_time = 0; // init
    cout << bfs(sy, sx, 1, n) << endl;
  }
  return 0;
}

#include <iostream>
#include <queue>

#define INF 1e9
#define MAX_H 1000
#define MAX_W 1000

using namespace std;

struct Cood {
  int x, y;
};

int N;
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};

char field[MAX_H][MAX_W + 1];
int d[MAX_H][MAX_W + 1];
queue<Cood> q;
int h, w, n;
int total_time = 0;

void init_bfs() {
  queue<Cood> new_q;
  swap(q, new_q);
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      d[i][j] = INF;
    }
  }
}
/* current position (y, x) with current power 'current' & last cheeese target is
 * 'last' */
int bfs(int sy, int sx, int target, int last) {
  init_bfs();
  int next_y, next_x;
  q.push(Cood{sx, sy});
  d[sy][sx] = 0;

  while (q.size()) {
    Cood current = q.front();
    q.pop();
    if (field[current.y][current.x] == '0' + target) {
      total_time += d[current.y][current.x];
      if (target == last) {
        return total_time;
      } else {
        return bfs(current.y, current.x, target + 1, last);
      }
    }

    for (int i = 0; i < 4; ++i) {
      next_y = current.y + dy[i];
      next_x = current.x + dx[i];
      if (0 <= next_y && next_y < h && 0 <= next_x && next_x < w &&
          field[next_y][next_x] != 'X' && d[next_y][next_x] == INF) {
        q.push(Cood{next_x, next_y});
        d[next_y][next_x] = d[current.y][current.x] + 1;
      }
    }
  }
}

int main() {
  // freopen("0558_1.in", "r", stdin);
  cin >> h >> w >> n;
  int sx, sy;
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      cin >> field[i][j];
      if (field[i][j] == 'S') {
        sy = i, sx = j;
      }
    }
  }
  total_time = 0; // init
  cout << bfs(sy, sx, 1, n) << endl;
  return 0;
}


#if 0
#cflags(-std = c++ 14 - Wall)
#endif
#include <iostream>
template <typename T> T input(std::istream &os = std::cin) {
  T t;
  os >> t;
  return t;
}

#include <numeric>
#include <queue>
#include <string>
#include <vector>

struct pos {
  int x, y;
  template <typename T> auto operator[](T &&t) const {
    return std::forward<T>(t)[y][x];
  }
};
template <typename F> struct itr {
  int r;
  std::pair<pos, int> t;
  F shortest;
  itr &operator++() {
    ++r;
    return *this;
  }
  int &operator*() {
    t = shortest(r, t.first.x, t.first.y);
    return t.second;
  }
  bool operator==(const itr &other) const { return r == other.r; }
  bool operator!=(const itr &other) const { return !(*this == other); }
};
template <typename F> itr<F> make_itr(const pos &p, F &&f) {
  return ++itr<F>{0, {p, 0}, f};
}
template <typename F> itr<F> make_itr(int r, F &&f) { return itr<F>{r, {}, f}; }

int main() {
  const auto H = input<int>();
  const auto W = input<int>();
  const auto N = input<int>();
  const std::vector<std::string> data = [H] {
    std::vector<std::string> data;
    data.reserve(H);
    for (int i = 0; i < H; ++i)
      data.emplace_back(input<std::string>());
    return data;
  }();
  const std::vector<pos> poss = [&] {
    std::vector<pos> poss(10);
    for (int j = 0; j < H; ++j)
      for (int i = 0; i < W; ++i)
        if (data[j][i] == 'S')
          poss[0] = {i, j};
        else if ('1' <= data[j][i] && data[j][i] <= '9')
          poss[data[j][i] - '0'] = {j, i};
    return poss;
  }();
  auto shortest = [&](int rank, int i, int j) {
    std::vector<std::vector<bool>> flags(H, std::vector<bool>(W));
    std::queue<std::pair<pos, int>> q;
    q.push({{i, j}, 0});
    while (true) {
      const auto &d = q.front();
      const auto &p = d.first;
      if (p[data] == rank + '0')
        return q.front();
      p[flags] = true;
      auto add = [&](const pos &po) {
        if (!po[flags])
          if (po[data] != 'X')
            q.push({po, d.second + 1});
          else
            p[flags] = true;
      };
      for (int a = -1; a <= 1; a += 2)
        if (0 <= p.x + a && p.x + a < W)
          add(pos{p.x + a, p.y});
      for (int b = -1; b <= 1; b += 2)
        if (0 <= p.y + b && p.y + b < H)
          add(pos{p.x, p.y + b});
      p[flags] = true;
      q.pop();
    }
    return q.front();
  };
  std::cout << std::accumulate(make_itr(poss[0], shortest),
                               make_itr(N + 1, shortest), 0)
            << std::endl;
}

#if 0
#cflags(-std = c++ 14 - Wall)
#endif
#include <iostream>
template <typename T> T input(std::istream &os = std::cin) {
  T t;
  os >> t;
  return t;
}

#include <numeric>
#include <queue>
#include <string>
#include <vector>

struct pos {
  int x, y;
  template <typename T> auto &&operator[](T &&t) const {
    return std::forward<T>(t)[y][x];
  }
};
template <typename F> struct itr {
  int r;
  std::pair<pos, int> t;
  F shortest;
  bool flag;
  itr &operator++() {
    ++r;
    flag = true;
    return *this;
  }
  int &operator*() {
    if (flag)
      t = shortest(r, t.first.x, t.first.y), flag = false;
    return t.second;
  }
  bool operator==(const itr &other) const { return r == other.r; }
  bool operator!=(const itr &other) const { return !(*this == other); }
};
template <typename F> itr<F> make_itr(const pos &p, F &&f) {
  return ++itr<F>{0, {p, 0}, f};
}
template <typename F> itr<F> make_itr(int r, F &&f) { return itr<F>{r, {}, f}; }

int main() {
  const auto H = input<int>();
  const auto W = input<int>();
  const auto N = input<int>();
  const std::vector<std::string> data = [H] {
    std::vector<std::string> data;
    data.reserve(H);
    for (int i = 0; i < H; ++i)
      data.emplace_back(input<std::string>());
    return data;
  }();
  const pos po = [&] {
    pos po;
    for (int j = 0; j < H; ++j)
      for (int i = 0; i < W; ++i)
        if (data[j][i] == 'S')
          po = {i, j};
    return po;
  }();
  auto shortest = [&](int rank, int i, int j) {
    std::vector<std::vector<char>> flags(H, std::vector<char>(W));
    std::queue<std::pair<pos, int>> q;
    q.push({{i, j}, 0});
    flags[j][i] = true;
    while (true) {
      const auto &d = q.front();
      const auto &p = d.first;
      if (p[data] == rank + '0')
        return q.front();
      p[flags] = true;
      auto add = [&](const pos &po) {
        if (!po[flags])
          if (po[data] != 'X')
            q.push({po, d.second + 1}), po[flags] = true;
          else
            po[flags] = true;
      };
      for (int a = -1; a <= 1; a += 2)
        if (0 <= p.x + a && p.x + a < W)
          add(pos{p.x + a, p.y});
      for (int b = -1; b <= 1; b += 2)
        if (0 <= p.y + b && p.y + b < H)
          add(pos{p.x, p.y + b});
      q.pop();
    }
    return q.front();
  };
  std::cout << std::accumulate(make_itr(po, shortest),
                               make_itr(N + 1, shortest), 0)
            << std::endl;
}


#include <iostream>
#include <queue>
#include <stdio.h>
#include <string.h>
using namespace std;

struct OZAWA {
  int x;
  int y;
  int c;
};
int Flag[1000][1000];
char MAP[1000][1000];
queue<OZAWA> Q;
OZAWA ba, v;
int main(void) {
  int H, W, N, Nc = 0, X[10], Y[10];
  int mv[4][2] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
  char Cheese[10] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
  memset(MAP, 'X', sizeof(MAP));
  memset(Flag, 0, sizeof(Flag));
  scanf("%d %d %d", &H, &W, &N);
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      // printf("%d %d ",i,j);
      cin >> MAP[i][j];
      // printf("Q");
      if (MAP[i][j] == 'S') {
        ba.x = j;
        ba.y = i;
        ba.c = 0;
        Flag[i][j] = 1;
        Q.push(ba);
        // printf("Sin\\n");
      }
      for (int ii = 0; ii < 9; ii++) {
        if (MAP[i][j] == Cheese[ii]) {

          X[ii] = j;
          Y[ii] = i;
          // printf("\\n@@@\\n");
        }
      }
    }
  }
  // printf("S %d %d\\n",ba.x,ba.y);
  // for(int ii=0;ii<2;ii++)
  // printf("%d %d\\n",X[0],Y[0]);
  while (!Q.empty()) {
    // printf("QA\\n");
    ba = Q.front();
    Q.pop();
    if (ba.x == X[Nc] && ba.y == Y[Nc]) {
      // printf("OZA");
      Nc++;
      memset(Flag, 0, sizeof(Flag));
      while (!Q.empty()) {
        Q.pop();
      }
      if (Nc == N)
        break;
      Q.push(ba);
      Flag[ba.y][ba.x] = 1;
    }
    // printf("aaa\\n");
    // if(Nc == N) break;
    for (int i = 0; i < 4; i++) {
      if (MAP[ba.y + mv[i][1]][ba.x + mv[i][0]] != 'X' &&
          Flag[ba.y + mv[i][1]][ba.x + mv[i][0]] == 0 &&
          (ba.x + mv[i][0]) >= 0 && (ba.x + mv[i][0]) < W &&
          (ba.y + mv[i][1]) >= 0 && (ba.y + mv[i][1]) < H) {
        v.x = ba.x + mv[i][0];
        v.y = ba.y + mv[i][1];
        v.c = ba.c + 1;
        Q.push(v);
        Flag[v.y][v.x] = 1;
        // printf("%d %d\\n",v.x,v.y);
      }
    }
  }
  cout << ba.c << endl;
  return 0;
}

#include <iostream>
#include <queue>
#include <stdio.h>
#include <string.h>
using namespace std;

struct OZAWA {
  int x;
  int y;
  int c;
};
int Flag[1001][1001];
char MAP[1001][1001];
queue<OZAWA> Q;
OZAWA ba, v;
int main(void) {
  int H, W, N, Nc = 0, X[10], Y[10];
  int mv[4][2] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
  char Cheese[10] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
  memset(MAP, 'X', sizeof(MAP));
  memset(Flag, 0, sizeof(Flag));
  scanf("%d %d %d", &H, &W, &N);
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      // printf("%d %d ",i,j);
      cin >> MAP[i][j];
      // printf("Q");
      if (MAP[i][j] == 'S') {
        ba.x = j;
        ba.y = i;
        ba.c = 0;
        Flag[i][j] = 1;
        Q.push(ba);
        // printf("Sin\\n");
      }
      for (int ii = 0; ii < 9; ii++) {
        if (MAP[i][j] == Cheese[ii]) {

          X[ii] = j;
          Y[ii] = i;
          // printf("\\n@@@\\n");
        }
      }
    }
  }
  // printf("S %d %d\\n",ba.x,ba.y);
  // for(int ii=0;ii<2;ii++)
  // printf("%d %d\\n",X[0],Y[0]);
  while (!Q.empty()) {
    // printf("QA\\n");
    ba = Q.front();
    Q.pop();
    if (ba.x == X[Nc] && ba.y == Y[Nc]) {
      // printf("OZA");
      Nc++;
      memset(Flag, 0, sizeof(Flag));
      while (!Q.empty()) {
        Q.pop();
      }
      if (Nc == N)
        break;
      Q.push(ba);
      Flag[ba.y][ba.x] = 1;
    }
    // printf("aaa\\n");
    // if(Nc == N) break;
    for (int i = 0; i < 4; i++) {
      if (MAP[ba.y + mv[i][1]][ba.x + mv[i][0]] != 'X' &&
          Flag[ba.y + mv[i][1]][ba.x + mv[i][0]] == 0 &&
          (ba.x + mv[i][0]) >= 0 && (ba.x + mv[i][0]) < W &&
          (ba.y + mv[i][1]) >= 0 && (ba.y + mv[i][1]) < H) {
        v.x = ba.x + mv[i][0];
        v.y = ba.y + mv[i][1];
        v.c = ba.c + 1;
        Q.push(v);
        Flag[v.y][v.x] = 1;
        // printf("%d %d\\n",v.x,v.y);
      }
    }
  }
  cout << ba.c << endl;
  return 0;
}


// AOJ 0558
// include
#include <bits/stdc++.h>

// using
using namespace std;

// define static const typedef
#define FOR(i, s, n) for (int i = s; i < int(n); i++)
#define REP(i, n) FOR((i), 0, (n))
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SORT(a) sort(ALL(a))
#define RSORT(a) sort(RALL(a))
#define DUMP(x) cerr << #x << " = " << x << "\\n";
#define DEBUG(x)                                                               \\
  cerr << #x << " = " << x << " (L:" << __LINE__ << ") " << __FILE__ << "\\n";
#define F first
#define S second

typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef vector<PII> VPII;
typedef long long LL;
typedef vector<LL> VLL;
typedef vector<VLL> VVLL;
typedef unsigned long long ULL;

static const int INF = 1 << 25;
static const int movex[] = {0, 0, 1, -1};
static const int movey[] = {1, -1, 0, 0};
// global
int a, b, c, ans, hp = 1;
VS mp;
int sx = INF, sy = INF;
string str = "";
char inp[1000];
vector<VVI> ar;
queue<pair<int, PII>> n;
// function
int main() {
  scanf("%d %d %d", &a, &b, &c);
  REP(i, b + 2) { str = str + "X"; }
  mp.PB(str);
  REP(i, a) {
    scanf("%s", inp);
    mp.PB(inp);
    mp[i + 1] = "X" + mp[i + 1] + "X";
    REP(j, mp[i + 1].size()) {
      if (sx != INF) {
        break;
      }
      if (mp[i + 1][j] == 'S') {
        sy = i + 1;
        sx = j;
        break;
      }
    }
  }
  ar.resize(c, VVI(a + 2, VI(b + 2)));
  REP(i, c) {
    REP(j, a + 2) {
      REP(k, b + 2) {
        ar[i][j][k] = INF;
        if (!i && sy == j && sx == k) {
          ar[0][j][k] = 0;
        }
      }
    }
  }
  mp.PB(str);
  n.push(pair<int, PII>(hp, PII(sy, sx)));

  while (!n.empty()) {
    if (n.front().F != hp) {
      n.pop();
      continue;
    }
    if (hp == mp[n.front().S.F][n.front().S.S] - '0') {
      hp++;
      if (hp > c) {
        ans = ar[c - 1][n.front().S.F][n.front().S.S];
        break;
      }
      ar[hp - 1][n.front().S.F][n.front().S.S] =
          ar[hp - 2][n.front().S.F][n.front().S.S];
    }
    int nowy = n.front().S.F, nowx = n.front().S.S;
    n.pop();
    REP(i, 4) {
      if (mp[nowy + movey[i]][nowx + movex[i]] != 'X' &&
          ar[hp - 1][nowy + movey[i]][nowx + movex[i]] >
              ar[hp - 1][nowy][nowx] + 1) {
        ar[hp - 1][nowy + movey[i]][nowx + movex[i]] =
            ar[hp - 1][nowy][nowx] + 1;
        n.push(pair<int, PII>(hp, PII(nowy + movey[i], nowx + movex[i])));
      }
    }
  }
  printf("%d\\n", ans);
  return 0;
}

// include
#include <bits/stdc++.h>

// using
using namespace std;

// define static const typedef
#define FOR(i, s, n) for (int i = s; i < int(n); i++)
#define REP(i, n) FOR((i), 0, (n))
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SORT(a) sort(ALL(a))
#define RSORT(a) sort(RALL(a))
#define DUMP(x) cerr << #x << " = " << x << "\\n";
#define DEBUG(x)                                                               \\
  cerr << #x << " = " << x << " (L:" << __LINE__ << ") " << __FILE__ << "\\n";
#define F first
#define S second

typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef vector<PII> VPII;
typedef long long LL;
typedef vector<LL> VLL;
typedef vector<VLL> VVLL;
typedef unsigned long long ULL;

static const int INF = 1 << 25;
static const int movex[] = {0, 0, 1, -1};
static const int movey[] = {1, -1, 0, 0};
// global
static int a, b, c, ans, hp = 1;
static VS mp;
static int sx = INF, sy = INF;
static string str = "";
static char inp[1000];
static vector<VVI> ar;
static queue<pair<int, PII>> n;
// function
int main() {
  scanf("%d %d %d", &a, &b, &c);
  REP(i, b + 2) { str = str + "X"; }
  mp.PB(str);
  REP(i, a) {
    scanf("%s", inp);
    mp.PB(inp);
    mp[i + 1] = "X" + mp[i + 1] + "X";
    REP(j, mp[i + 1].size()) {
      if (sx != INF) {
        break;
      }
      if (mp[i + 1][j] == 'S') {
        sy = i + 1;
        sx = j;
        break;
      }
    }
  }
  ar.resize(c, VVI(a + 2, VI(b + 2)));
  REP(i, c) {
    REP(j, a + 2) {
      REP(k, b + 2) {
        ar[i][j][k] = INF;
        if (!i && sy == j && sx == k) {
          ar[0][j][k] = 0;
        }
      }
    }
  }
  mp.PB(str);
  n.push(pair<int, PII>(hp, PII(sy, sx)));

  while (!n.empty()) {
    if (n.front().F != hp) {
      n.pop();
      continue;
    }
    if (hp == mp[n.front().S.F][n.front().S.S] - '0') {
      hp++;
      if (hp > c) {
        ans = ar[c - 1][n.front().S.F][n.front().S.S];
        break;
      }
      ar[hp - 1][n.front().S.F][n.front().S.S] =
          ar[hp - 2][n.front().S.F][n.front().S.S];
    }
    int nowy = n.front().S.F, nowx = n.front().S.S;
    n.pop();
    REP(i, 4) {
      if (mp[nowy + movey[i]][nowx + movex[i]] != 'X' &&
          ar[hp - 1][nowy + movey[i]][nowx + movex[i]] >
              ar[hp - 1][nowy][nowx] + 1) {
        ar[hp - 1][nowy + movey[i]][nowx + movex[i]] =
            ar[hp - 1][nowy][nowx] + 1;
        n.push(pair<int, PII>(hp, PII(nowy + movey[i], nowx + movex[i])));
      }
    }
  }
  printf("%d\\n", ans);
  return 0;
}


#include "bits/stdc++.h"

using namespace std;

// #define int long long

#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define REP(i, n) for (int i = 0; i < (n); i++)

#define pb push_back
#define VDEL(v, n) v.erase(v.begin() + (n))
#define ALL(v) v.begin(), v.end()

#define INTMAX 2147483647
#define INF 200000000
#define TINT(str) atoi(str.c_str())
#define TSTR(num) to_string(num)

typedef long long ll;
typedef pair<int, int> PII;
typedef vector<int> VI;
typedef vector<vector<int>> VII;

int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};

PII goal[10];
char k[1000][1000];
int fx, fy;
int H, W;

int BFS(int x, int y) {
  VII cost;
  cost = VII(H, VI(W, INT_MAX));

  cost[fx][fy] = 0;

  queue<PII> q;

  q.push(make_pair(fx, fy));

  while (!q.empty()) {
    PII now = q.front();
    q.pop();
    int nx = now.first;
    int ny = now.second;

    if (nx == x && ny == y) {
      return cost[nx][ny];
    }

    REP(i, 4) {
      if (nx + dx[i] >= H || nx + dx[i] < 0)
        continue;
      if (ny + dy[i] >= W || ny + dy[i] < 0)
        continue;

      if (k[nx + dx[i]][ny + dy[i]] != 'X') {
        if (cost[nx + dx[i]][ny + dy[i]] > cost[nx][ny]) {
          cost[nx + dx[i]][ny + dy[i]] = cost[nx][ny] + 1;
          q.push(make_pair(nx + dx[i], ny + dy[i]));
        }
      }
    }
  }

  return -1;
}

signed main() {
  int N;
  cin >> H >> W >> N;

  char str[1001];
  REP(h, H) {
    scanf("%s", str);
    REP(w, W) {
      k[h][w] = str[w];
      if (k[h][w] == 'S') {
        fx = h;
        fy = w;
      }
      if (k[h][w] != '.' && k[h][w] != 'X') {
        goal[k[h][w] - '1'] = make_pair(h, w);
      }
    }
  }
  int ans = 0;

  REP(i, N) {
    ans += BFS(goal[i].first, goal[i].second);
    fx = goal[i].first;
    fy = goal[i].second;
  }

  cout << ans << endl;

  return 0;
}

#include "bits/stdc++.h"

using namespace std;

// #define int long long

#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define REP(i, n) for (int i = 0; i < (n); i++)

#define pb push_back
#define VDEL(v, n) v.erase(v.begin() + (n))
#define ALL(v) v.begin(), v.end()

#define INTMAX 2147483647
#define INF 200000000
#define TINT(str) atoi(str.c_str())
#define TSTR(num) to_string(num)

typedef long long ll;
typedef pair<int, int> PII;
typedef vector<int> VI;
typedef vector<vector<int>> VII;

int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};

PII goal[10];
char k[1000][1000];
int fx, fy;
int H, W;

int BFS(int x, int y) {
  VII cost;
  cost = VII(H, VI(W, INT_MAX));

  cost[fx][fy] = 0;

  queue<PII> q;

  q.push(make_pair(fx, fy));

  while (!q.empty()) {
    PII now = q.front();
    q.pop();
    int nx = now.first;
    int ny = now.second;

    if (nx == x && ny == y) {
      return cost[nx][ny];
    }

    REP(i, 4) {
      if (nx + dx[i] >= H || nx + dx[i] < 0)
        continue;
      if (ny + dy[i] >= W || ny + dy[i] < 0)
        continue;

      if (k[nx + dx[i]][ny + dy[i]] != 'X') {
        if (cost[nx + dx[i]][ny + dy[i]] > cost[nx][ny] + 1) {
          cost[nx + dx[i]][ny + dy[i]] = cost[nx][ny] + 1;
          q.push(make_pair(nx + dx[i], ny + dy[i]));
        }
      }
    }
  }

  return -1;
}

signed main() {
  int N;
  cin >> H >> W >> N;

  char str[1001];
  REP(h, H) {
    scanf("%s", str);
    REP(w, W) {
      k[h][w] = str[w];
      if (k[h][w] == 'S') {
        fx = h;
        fy = w;
      }
      if (k[h][w] != '.' && k[h][w] != 'X') {
        goal[k[h][w] - '1'] = make_pair(h, w);
      }
    }
  }
  int ans = 0;

  REP(i, N) {
    ans += BFS(goal[i].first, goal[i].second);
    fx = goal[i].first;
    fy = goal[i].second;
  }

  cout << ans << endl;

  return 0;
}


// 14:54
#include <queue>
#include <stdio.h>

using namespace std;

typedef pair<int, int> P;

int h, w, n;
char field[100][101];
queue<P> qu;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int d[100][100];

void init() {
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      d[i][j] = -1;
    }
  }
  queue<P> empty;
  swap(qu, empty);
}

int solve() {
  int hp = 1;
  int cnt;
  init();
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (field[i][j] == 'S') {
        qu.push(P(i, j));
        d[i][j] = 0;
      }
    }
  }
  while (qu.size()) {
    P p = qu.front();
    qu.pop();
    int y = p.first;
    int x = p.second;
    if (hp == n + 1)
      return d[y][x];
    if (hp == field[y][x] - '0') {
      hp++;
      cnt = d[y][x];
      init();
      d[y][x] = cnt;
    }
    for (int i = 0; i < 4; i++) {
      int ny = y + dy[i];
      int nx = x + dx[i];
      if (ny >= 0 && ny < h && nx >= 0 && nx < w && field[ny][nx] != 'X' &&
          d[ny][nx] == -1) {
        d[ny][nx] = d[y][x] + 1;
        qu.push(P(ny, nx));
      }
    }
  }
  return 0;
}

int main() {
  scanf("%d %d %d", &h, &w, &n);
  for (int i = 0; i < h; i++) {
    scanf("%s", field[i]);
  }
  printf("%d\\n", solve() - 1);
  return 0;
}

// 14:54
#include <queue>
#include <stdio.h>

using namespace std;

typedef pair<int, int> P;

int h, w, n;
char field[1000][1001];
queue<P> qu;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int d[1000][1000];

void init() {
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      d[i][j] = -1;
    }
  }
  queue<P> empty;
  swap(qu, empty);
}

int solve() {
  int hp = 1;
  int cnt;
  init();
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (field[i][j] == 'S') {
        qu.push(P(i, j));
        d[i][j] = 0;
      }
    }
  }
  while (qu.size()) {
    P p = qu.front();
    qu.pop();
    int y = p.first;
    int x = p.second;
    if (hp == n + 1)
      return d[y][x];
    if (hp == field[y][x] - '0') {
      hp++;
      cnt = d[y][x];
      init();
      d[y][x] = cnt;
    }
    for (int i = 0; i < 4; i++) {
      int ny = y + dy[i];
      int nx = x + dx[i];
      if (ny >= 0 && ny < h && nx >= 0 && nx < w && field[ny][nx] != 'X' &&
          d[ny][nx] == -1) {
        d[ny][nx] = d[y][x] + 1;
        qu.push(P(ny, nx));
      }
    }
  }
  return 0;
}

int main() {
  scanf("%d %d %d", &h, &w, &n);
  for (int i = 0; i < h; i++) {
    scanf("%s", field[i]);
  }
  printf("%d\\n", solve() - 1);
  return 0;
}


#include <cctype>
#include <cstdio>
#include <queue>

#define mp make_pair
#define rep(i, n) for (int i = 0; i < n; i++)

using namespace std;

typedef pair<int, int> pii;

const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};

int h, w;
char grid[1000][1001];

int shortestDistance(int sx, int sy, int gx, int gy) {
  static bool visited[1000][1000];
  rep(i, h) rep(j, w) visited[i][j] = false;
  visited[sy][sx] = true;

  queue<pair<int, pii>> qu;
  qu.push(mp(0, mp(sx, sy)));
  while (1) {
    pair<int, pii> a = qu.front();
    qu.pop();
    int d = a.first, x = a.second.first, y = a.second.second;
    if (x == gx && y == gy)
      return d;

    rep(i, 4) {
      int xx = x + dx[i], yy = y + dy[i];
      if (0 <= xx && xx < w && 0 <= yy && yy < h && grid[yy][xx] != 'X' &&
          !visited[yy][xx]) {
        visited[y][x] = true;
        qu.push(mp(d + 1, mp(xx, yy)));
      }
    }
  }
}

int main() {
  int n;
  scanf("%d%d%d", &h, &w, &n);
  int cx[10], cy[10];
  rep(i, h) {
    scanf("%s", grid[i]);
    rep(j, w) {
      if (grid[i][j] == 'S')
        cx[0] = j, cy[0] = i;
      if (isdigit(grid[i][j]))
        cx[grid[i][j] - '0'] = j, cy[grid[i][j] - '0'] = i;
    }
  }

  int cost = 0;
  rep(i, n) cost += shortestDistance(cx[i], cy[i], cx[i + 1], cy[i + 1]);
  printf("%d\\n", cost);

  return 0;
}

#include <cctype>
#include <cstdio>
#include <queue>

#define mp make_pair
#define rep(i, n) for (int i = 0; i < n; i++)

using namespace std;

typedef pair<int, int> pii;

const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};

int h, w;
char grid[1000][1001];

int shortestDistance(int sx, int sy, int gx, int gy) {
  static bool visited[1000][1000];
  rep(i, h) rep(j, w) visited[i][j] = false;
  visited[sy][sx] = true;

  queue<pair<int, pii>> qu;
  qu.push(mp(0, mp(sy, sx)));
  while (1) {
    pair<int, pii> a = qu.front();
    qu.pop();
    int d = a.first, x = a.second.second, y = a.second.first;
    if (x == gx && y == gy)
      return d;

    rep(i, 4) {
      int xx = x + dx[i], yy = y + dy[i];
      if (0 <= xx && xx < w && 0 <= yy && yy < h && grid[yy][xx] != 'X' &&
          !visited[yy][xx]) {
        visited[yy][xx] = true;
        qu.push(mp(d + 1, mp(yy, xx)));
      }
    }
  }
}

int main() {
  int n;
  scanf("%d%d%d", &h, &w, &n);
  int cx[10], cy[10];
  rep(i, h) {
    scanf("%s", grid[i]);
    rep(j, w) {
      if (grid[i][j] == 'S')
        cx[0] = j, cy[0] = i;
      if (isdigit(grid[i][j]))
        cx[grid[i][j] - '0'] = j, cy[grid[i][j] - '0'] = i;
    }
  }

  int cost = 0;
  rep(i, n) cost += shortestDistance(cx[i], cy[i], cx[i + 1], cy[i + 1]);
  printf("%d\\n", cost);

  return 0;
}


#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <queue>
#define INF 1000000
using namespace std;
typedef pair<int, int> P;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
bool map[1000][1000];
int x[10], y[10];
int ans = 0;
int h, w;
int search(int n) {
  int d[1000][1000];
  fill(d[0], d[0] + 1000 * 1000, INF);
  int sx = x[n], sy = y[n];
  int tx = x[n + 1], ty = y[n + 1];
  queue<P> q;
  q.push(P(sx, sy));
  d[sx][sy] = 0;
  while (!q.empty()) {
    P p = q.front();
    q.pop();
    sx = p.first, sy = p.second;
    if (sx == tx && sy == ty)
      return d[tx][ty];
    for (int i = 0; i < 4; i++) {
      int X = sx + dx[i];
      int Y = sy + dy[i];
      if (map[X][Y] && X >= 0 && X < h && Y >= 0 && Y < w && d[X][Y] == INF) {
        q.push(P(X, Y));
        d[X][Y] = d[sx][sy] + 1;
      }
    }
  }
  return d[tx][ty];
}
int main() {
  int n;
  scanf("%d %d %d", &h, &w, &n);
  fill(map[0], map[0] + 1000 * 1000, false);
  getchar();
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      char c = getchar();
      if (c != 'X') {
        map[i][j] = true;
        if (c == 'S') {
          x[0] = i, y[0] = j;
        } else {
          int k = (int)c - 48;
          x[k] = i;
          y[k] = j;
        }
      }
    }
    getchar();
  }
  for (int i = 0; i < n; i++) {
    int tmp = search(i);
    ans += tmp;
  }
  printf("%d\\n", ans);
  return 0;
}

#include <algorithm>
#include <cstdio>
#include <queue>
#define INF 1000000
using namespace std;
typedef pair<int, int> P;
int h, w, n, ans = 0;
bool map[1002][1002];
int x[10], y[10];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {-1, 0, 1, 0};
int main() {
  scanf("%d %d %d", &h, &w, &n);
  fill(map[0], map[0] + 1002 * 1002, false);
  for (int i = 1; i <= h; i++) {
    getchar();
    for (int j = 1; j <= w; j++) {
      char c = getchar();
      if (c != 'X') {
        map[i][j] = true;
        if (c == 'S') {
          x[0] = i;
          y[0] = j;
        } else if (c != '.') {
          x[c - 48] = i;
          y[c - 48] = j;
        }
      }
    }
  }
  for (int i = 0; i < n; i++) {
    int d[1002][1002];
    fill(d[0], d[0] + 1002 * 1002, INF);
    queue<P> q;
    d[x[i]][y[i]] = 0;
    q.push(P(x[i], y[i]));
    while (!q.empty()) {
      P p = q.front();
      int sx = p.first;
      int sy = p.second;
      q.pop();
      if (sx == x[i + 1] && sy == y[i + 1])
        break;
      for (int j = 0; j < 4; j++) {
        if (map[sx + dx[j]][sy + dy[j]] && d[sx + dx[j]][sy + dy[j]] == INF) {
          d[sx + dx[j]][sy + dy[j]] = d[sx][sy] + 1;
          q.push(P(sx + dx[j], sy + dy[j]));
        }
      }
    }
    ans += d[x[i + 1]][y[i + 1]];
  }
  printf("%d\\n", ans);
}


#include <cstdlib>
#include <iostream>
#include <queue>
#include <sstream>

using namespace std;

const int INF = 100000000;
const int MAX_W = 1000;
const int MAX_H = 1000;
int H, W, N;
char field[MAX_H][MAX_W] = {'X'};
int d[MAX_H][MAX_W] = {INF};
typedef pair<int, int> P;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};

int main() {
  queue<P> que;
  P start;
  int pow = 1;
  while (std::cin >> H >> W >> N, H) {
    for (int i = 0; i < H; i++) {
      std::cin >> field[i];
    }
    for (int i = 0; i < H; i++) {
      for (int j = 0; j < W; j++) {
        d[i][j] = INF;
        if (field[i][j] == 'S') {
          start = P(i, j);
        }
      }
    }
    que.push(start);
    d[start.first][start.second] = 0;
    int count = 0;
    while (que.size()) {
      P p = que.front();
      que.pop();
      if (field[p.first][p.second] == '0' + N and N <= pow) {
        count = d[p.first][p.second];
        break;
      }

      for (int i = 0; i < 4; i++) {
        int nx = p.second + dx[i];
        int ny = p.first + dy[i];
        if (nx >= 0 and ny >= 0 and nx < W and ny < H and
            field[ny][nx] != 'X' and d[ny][nx] == INF) {
          if (field[ny][nx] == '.') {
            que.push(P(ny, nx));
            d[ny][nx] = d[p.first][p.second] + 1;
          } else {
            if (field[ny][nx] <= '0' + pow) {
              // cout << "pow:" << pow << ", cheese:" << field[ny][nx] << endl;
              int s = d[p.first][p.second];
              field[ny][nx] = '.';
              for (int i = 0; i < H; i++) {
                for (int j = 0; j < W; j++) {
                  d[i][j] = INF;
                }
              }

              while (que.size()) {
                que.pop();
              }
              que.push(P(ny, nx));
              d[ny][nx] = s + 1;
              if (pow == N) {
                field[ny][nx] = '0' + N;
              }
              pow++;
              break;
            } else {
              que.push(P(ny, nx));
              d[ny][nx] = d[p.first][p.second] + 1;
            }
          }
        }
      }
    }

    std::cout << count << std::endl;
    break;
  }

  return 0;
}

#include <cstdlib>
#include <iostream>
#include <queue>
#include <sstream>

using namespace std;

const int INF = 100000000;
const int MAX_W = 1001;
const int MAX_H = 1001;
int H, W, N;
char field[MAX_H][MAX_W] = {'X'};
int d[MAX_H][MAX_W] = {INF};
typedef pair<int, int> P;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};

int main() {
  queue<P> que;
  P start;
  int pow = 1;
  while (std::cin >> H >> W >> N, H) {
    for (int i = 0; i < H; i++) {
      std::cin >> field[i];
    }
    for (int i = 0; i < H; i++) {
      for (int j = 0; j < W; j++) {
        d[i][j] = INF;
        if (field[i][j] == 'S') {
          start = P(i, j);
        }
      }
    }
    que.push(start);
    d[start.first][start.second] = 0;
    int count = 0;
    while (que.size()) {
      P p = que.front();
      que.pop();
      if (field[p.first][p.second] == '0' + N and N <= pow) {
        count = d[p.first][p.second];
        break;
      }

      for (int i = 0; i < 4; i++) {
        int nx = p.second + dx[i];
        int ny = p.first + dy[i];
        if (nx >= 0 and ny >= 0 and nx < W and ny < H and
            field[ny][nx] != 'X' and d[ny][nx] == INF) {
          if (field[ny][nx] == '.') {
            que.push(P(ny, nx));
            d[ny][nx] = d[p.first][p.second] + 1;
          } else {
            if (field[ny][nx] <= '0' + pow) {
              // cout << "pow:" << pow << ", cheese:" << field[ny][nx] << endl;
              int s = d[p.first][p.second];
              field[ny][nx] = '.';
              for (int i = 0; i < H; i++) {
                for (int j = 0; j < W; j++) {
                  d[i][j] = INF;
                }
              }

              while (que.size()) {
                que.pop();
              }
              que.push(P(ny, nx));
              d[ny][nx] = s + 1;
              if (pow == N) {
                field[ny][nx] = '0' + N;
              }
              pow++;
              break;
            } else {
              que.push(P(ny, nx));
              d[ny][nx] = d[p.first][p.second] + 1;
            }
          }
        }
      }
    }

    std::cout << count << std::endl;
    break;
  }

  return 0;
}


#include <cstdio>
#include <iostream>
#include <queue>
using namespace std;

int h, w, n;
const int MAX_N = 1005;
char map[MAX_N][MAX_N];
struct point {
  int x, y;
  int step;
  point() {
    x = 0;
    y = 0;
    step = 0;
  }
  point(int xx, int yy, int ss) {
    x = xx;
    y = yy;
    step = ss;
  }
};
struct point p[16];

int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

int ok(int x, int y) {
  if (x >= 0 && x < h && y >= 0 && y < w)
    return 1;
  return 0;
}

int bfs(int next) {
  int nextcheese = next + 1;

  queue<point> q;
  point cur(p[next].x, p[next].y, 0);
  q.push(cur);
  while (q.size()) {
    cur = q.front();
    q.pop();
    int x = cur.x, y = cur.y;
    int nx, ny;
    for (int i = 0; i < 4; i++) {
      nx = x + dx[i];
      ny = y + dy[i];
      if (ok(nx, ny)) {
        if ((map[nx][ny] - '0') == nextcheese)
          return ++cur.step;
        if (map[nx][ny] == '.') {
          q.push(point(nx, ny, cur.step + 1));
        }
      }
    }
  }
}

void solve() {
  cin >> h >> w >> n;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      cin >> map[i][j];
    }
  }
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      char ch = map[i][j];
      switch (ch) {
      case '.':
        break;
      case 'X':
        break;
      case 'S':
        p[0].x = i;
        p[0].y = j;
        map[i][j] = '.';
        break;
      default:
        int t = (ch - '0');
        p[t].x = i;
        p[t].y = j;
      }
      /* if(map[i][j]=='S'){
           p[0].x=i; p[0].y = j;
           map[i][j]='.';
       }
       else if(isdigit(map[i][j])){
           int index=map[i][j]-'0';
           p[index].x=i; p[index].y=j;
       }*/
    }
  }
  int step = 0;
  for (int i = 0; i < n; i++) {
    step += bfs(i);
  }
  printf("%d\\n", step);
}

int main() { solve(); }

#include <iostream>
#include <queue>
using namespace std;
int w, h, n;
char map[1024][1024];
// 各点到当前工厂的距离
int d[1024][1024];
const int direction[4][2] = {
    {-1, 0},
    {1, 0},
    {0, -1},
    {0, 1},
};

int factory[16][2];
typedef pair<int, int> P;

//************************************
// Method:    bfs
// FullName:  bfs
// Access:    public
// Returns:   int
// Qualifier:
// Parameter: const int & sx 起点x
// Parameter: const int & sy 起点y
// Parameter: const int & gx 终点x
// Parameter: const int & gy 终点y
//************************************
int bfs(const int &sx, const int &sy, const int &gx, const int &gy) {
  // memset(d, -1, sizeof(d));
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      d[j][i] = -1;
    }
  }
  queue<P> que;
  que.push(P(sx, sy));
  d[sx][sy] = 0;
  while (que.size()) {
    const P p = que.front();
    que.pop();
    // 如果是终点就结束
    if (p.first == gx && p.second == gy) {
      break;
    }

    // 四方向漫游
    for (int i = 0; i < 4; ++i) {
      int nx = p.first + direction[i][0];
      int ny = p.second + direction[i][1];
      // 是否可以移动，并且该点没有访问过
      if (0 <= nx && nx < w && 0 <= ny && ny < h && map[nx][ny] != 'X' &&
          d[nx][ny] == -1) {
        que.push(P(nx, ny));
        d[nx][ny] = d[p.first][p.second] + 1;
      }
    }
  }

  return d[gx][gy];
}

///////////////////////////SubMain//////////////////////////////////
int main(int argc, char *argv[]) {

  cin >> h >> w >> n;
  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      cin >> map[j][i];
    }
  }

  for (int i = 0; i < h; ++i) {
    for (int j = 0; j < w; ++j) {
      if (map[j][i] == 'S') {
        factory[0][0] = j;
        factory[0][1] = i;
        map[j][i] = '.';
      } else if (isdigit(map[j][i])) {
        int index = map[j][i] - '0';
        factory[index][0] = j;
        factory[index][1] = i;
      }
    }
  }

  int step = 0;
  for (int i = 0; i < n; ++i) {
    // 按顺序吃遍中华
    step +=
        bfs(factory[i][0], factory[i][1], factory[i + 1][0], factory[i + 1][1]);
  }

  cout << step << endl;

  return 0;
}


#include <iostream>
using namespace std;

int main() {

  int a, b, c;
  int s, ch, e, d;
  s = ch = e = d = 0;

  while (1) {
    cin >> a >> b >> c;
    if (a == 0)
      break;
    s++;
    a = a * a;
    b = b * b;
    c = c * c;
    int hantei;
    if (a > b) {
      if (a > c) {
        hantei = a - b - c;
      } else {
        hantei = c - a - b;
      }
    } else {
      if (b > c) {
        hantei = b - a - c;
      } else {
        hantei = c - a - b;
      }
    }
    if (hantei > 0) {
      d++;
    } else if (hantei < 0) {
      e++;
    } else {
      ch++;
    }
  }

  cout << s << " " << ch << " " << e << " " << d << endl;

  return 0;
}

#include <iostream>
using namespace std;

int main() {

  int a, b, c;
  int s, ch, e, d;
  s = ch = e = d = 0;
  int tmp, hantei;
  while (1) {
    cin >> a >> b >> c;
    if (a > b) {
      if (a > c) {
        tmp = a;
        a = c;
        c = tmp;
      }
    } else {
      if (b > c) {
        tmp = b;
        b = c;
        c = tmp;
      }
    }
    if (c >= a + b)
      break;
    s++;
    hantei = c * c - a * a - b * b;
    if (hantei > 0) {
      d++;
    } else if (hantei < 0) {
      e++;
    } else {
      ch++;
    }
  }

  cout << s << " " << ch << " " << e << " " << d << endl;

  return 0;
}


#include <algorithm>
#include <iostream>
using namespace std;
int main() {
  int a[3];
  bool b = true;
  int w, x, y, z;
  while (cin) {
    if (b) {
      w++;
      sort(a, a + 3);
      if (a[0] + a[1] < a[2]) {
        b = false;
      } else if (a[0] * a[0] + a[1] * a[1] == a[2] * a[2])
        x++;
      else if (a[0] * a[0] + a[1] * a[1] < a[2] * a[2])
        y++;
      else
        z++;
    }
  }
  cout << w << ' ' << x << ' ' << y << ' ' << z << endl;
}

#include <algorithm>
#include <iostream>
using namespace std;
int main() {
  int a[3];
  bool b = true;
  unsigned w, x, y, z;
  x = 0;
  y = 0;
  z = 0;
  while (cin >> a[0] >> a[1] >> a[2]) {
    if (b) {
      sort(a, a + 3);
      if (a[0] + a[1] < a[2])
        b = false;
      else if (a[0] * a[0] + a[1] * a[1] == a[2] * a[2])
        x++;
      else if (a[0] * a[0] + a[1] * a[1] < a[2] * a[2])
        z++;
      else
        y++;
    }
  }
  cout << x + y + z << ' ' << x << ' ' << y << ' ' << z << endl;
}


#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, q, s, t;
  long long a[200000];
  vector<long long> vec;
  cin >> n >> q >> s >> t;
  for (int i = 0; i <= n; i++)
    cin >> a[i];
  int l, r, x;
  long long ans;
  for (int i = 0; i < q; i++) {
    cin >> l >> r >> x;
    ans = 0;
    for (int j = l; j <= r; j++)
      a[j] += x;
    for (int i = 0; i <= n; i++) {
      if (i != 0) {
        if (a[i - 1] < a[i])
          ans -= s * (a[i] - a[i - 1]);
        if (a[i - 1] > a[i])
          ans += t * (a[i - 1] - a[i]);
      }
    }
    cout << ans << endl;
  }
  return (0);
}

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, q, s, t, a, b, l, r, x;
  long long ans = 0;
  cin >> n >> q >> s >> t;
  vector<long long> vec;
  for (int i = 0; i <= n; i++) {
    cin >> a;
    if (i != 0) {
      vec.push_back(a - b);
      if (vec[i - 1] > 0)
        ans -= vec[i - 1] * s;
      else
        ans -= vec[i - 1] * t;
    }
    b = a;
  }
  vec.push_back(0);
  for (int i = 0; i < q; i++) {
    cin >> l >> r >> x;
    if (vec[l - 1] > 0)
      ans += vec[l - 1] * s;
    else
      ans += vec[l - 1] * t;
    if (vec[r] > 0)
      ans += vec[r] * s;
    else
      ans += vec[r] * t;
    vec[l - 1] += x;
    if (r != n)
      vec[r] -= x;
    if (vec[l - 1] > 0)
      ans -= vec[l - 1] * s;
    else
      ans -= vec[l - 1] * t;
    if (vec[r] > 0)
      ans -= vec[r] * s;
    else
      ans -= vec[r] * t;
    cout << ans << endl;
  }
  return (0);
}


#include "bits/stdc++.h"
#define MOD 1000000007
#define INF 11234567890
#define in std::cin
#define out std::cout
#define rep(i, N) for (int i = 0; i < N; ++i)
typedef long long int LL;

LL N, Q, S, T, A[212345], L[212345], R[212345], X[212345];
LL ans;

int main() {
  in >> N >> Q >> S >> T;
  rep(i, N + 1) { in >> A[i]; }
  rep(i, Q) { in >> L[i] >> R[i] >> X[i]; }

  rep(i, Q) {
    ans = 0;
    for (int j = L[i]; j <= R[i]; ++j) {
      A[j] += X[i];
    }
    rep(j, N) {
      if (A[j] < A[j + 1]) {
        ans -= S * (A[j + 1] - A[j]);
      } else {
        ans += T * (A[j] - A[j + 1]);
      }
    }
    out << ans << std::endl;
  }
  return 0;
}


#include <iostream>
#include <vector>
using namespace std;
typedef long long ll;
int N, Q, S, T, L, R, X, d[100009];
ll ret;
void change_d(int pos, int x) {
  if (pos < N) {
    if (d[pos] > 0)
      ret += 1LL * S * d[pos];
    if (d[pos] < 0)
      ret += 1LL * T * d[pos];
  }
  d[pos] += x;
  if (pos < N) {
    if (d[pos] > 0)
      ret -= 1LL * S * d[pos];
    if (d[pos] < 0)
      ret -= 1LL * T * d[pos];
  }
}
void change(int l, int r, int x) {
  change_d(l - 1, x);
  change_d(r - 1, -x);
}
int main() {
  cin >> N >> Q >> S >> T;
  for (int i = 0; i <= N; i++) {
    cin >> X;
    if (i >= 1)
      change(i, i + 1, X);
  }
  for (int i = 0; i < Q; i++) {
    cin >> L >> R >> X;
    change(L, R + 1, X);
    cout << ret << endl;
  }
  return 0;
}

#include <iostream>
using namespace std;
int N, Q, S, T, L, R, X;
long long d[200009], ret;
void change_d(int pos, int x) {
  if (pos < N) {
    if (d[pos] > 0)
      ret += 1LL * S * d[pos];
    if (d[pos] < 0)
      ret += 1LL * T * d[pos];
  }
  d[pos] += x;
  if (pos < N) {
    if (d[pos] > 0)
      ret -= 1LL * S * d[pos];
    if (d[pos] < 0)
      ret -= 1LL * T * d[pos];
  }
}
void change(int l, int r, int x) {
  change_d(l - 1, x);
  change_d(r - 1, -x);
}
int main() {
  ios::sync_with_stdio(false);
  cin >> N >> Q >> S >> T;
  for (int i = 0; i <= N; i++) {
    cin >> X;
    if (i >= 1)
      change(i, i + 1, X);
  }
  for (int i = 0; i < Q; i++) {
    cin >> L >> R >> X;
    change(L, R + 1, X);
    cout << ret << endl;
  }
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main(void) {
  ll N, Q, S, T;
  cin >> N >> Q >> S >> T;
  vector<ll> A(N + 1);
  vector<ll> B(N);
  for (ll i = 0; i <= N; i++) {
    cin >> A[i];
  }

  for (ll i = 1; i <= N; i++) {
    B[i - 1] = A[i] - A[i - 1];
  }

  ll ans = 0;
  for (int i = 0; i < N; i++) {
    if (B[i] > 0) {
      ans -= B[i] * S;
    } else {
      ans -= B[i] * T;
    }
  }

  for (int i = 0; i < Q; i++) {
    ll l, r, x;
    cin >> l >> r >> x;
    l--;

    if (B[l] > 0)
      ans += B[l] * S;
    else
      ans += B[l] * T;

    if (r != N) {
      if (B[r] > 0)
        ans += B[r] * S;
      else
        ans += B[r] * T;
    }

    B[l] += x;
    B[r] -= x;
    if (B[l] > 0) {
      ans -= B[l] * S;
    } else {
      ans -= B[l] * T;
    }

    if (r != N) {
      if (B[r] > 0) {
        ans -= B[r] * S;
      } else {
        ans -= B[r] * T;
      }
    }

    cout << ans << endl;
  }
  return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main(void) {
  ll N, Q, S, T;
  cin >> N >> Q >> S >> T;
  vector<ll> A(N + 1);
  vector<ll> B(N);
  for (ll i = 0; i <= N; i++) {
    cin >> A[i];
  }

  for (ll i = 1; i <= N; i++) {
    B[i - 1] = A[i] - A[i - 1];
  }

  ll ans = 0;
  for (int i = 0; i < N; i++) {
    if (B[i] > 0) {
      ans -= B[i] * S;
    } else {
      ans -= B[i] * T;
    }
  }

  for (int i = 0; i < Q; i++) {
    ll l, r, x;
    cin >> l >> r >> x;
    l--;

    if (B[l] > 0)
      ans += B[l] * S;
    else
      ans += B[l] * T;

    if (r != N) {
      if (B[r] > 0)
        ans += B[r] * S;
      else
        ans += B[r] * T;
    }

    B[l] += x;
    if (r != N)
      B[r] -= x;
    if (B[l] > 0) {
      ans -= B[l] * S;
    } else {
      ans -= B[l] * T;
    }

    if (r != N) {
      if (B[r] > 0) {
        ans -= B[r] * S;
      } else {
        ans -= B[r] * T;
      }
    }

    cout << ans << endl;
  }
  return 0;
}


#include <bits/stdc++.h>

#define X first
#define Y second
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define rep(i, a, b) for (unsigned i = (a); i <= (b); ++i)
#define per(i, a, b) for (unsigned i = (a); i >= (b); --i)

using namespace std;

using I = int;
using L = long;
using F = float;
using S = string;
using SS = stringstream;
using C = char;
using LL = long long;
using VI = vector<int>;
using VL = vector<long>;
using VF = vector<float>;
using VS = vector<string>;
using PLL = pair<long, long>;
using PLF = pair<long, float>;
using PLS = pair<long, string>;
using PSL = pair<string, long>;
using PSF = pair<string, float>;
using PSS = pair<string, string>;
using MLL = map<long, long>;
using MLF = map<long, float>;
using MLS = map<long, string>;
using MSL = map<string, long>;
using MSF = map<string, float>;
using MSS = map<string, string>;

const long kMax2 = 109;
const long kMax3 = 1009;
const long kMax4 = 10009;
const long kMax5 = 100009;
const long kMax6 = 1000009;
const long kInfI = 0x3F3F3F3F;
const float kInfF = 1e15;

int main(int argc, char const *argv[]) {
  L n, q, s, t;
  VL a;
  cin >> n >> q >> s >> t;
  L prev_h = 0;
  L h;
  rep(i, 0, n) {
    cin >> h;
    if (i == 0) {
      continue;
    }
    a.pb(h - prev_h);
    prev_h = h;
  }

  rep(i, 1, q) {
    L l, r, x;
    cin >> l >> r >> x;
    L temp = 0;
    a[l - 1] += x;
    if (r != n) {
      a[r] -= x;
    }

    rep(i, 0, n - 1) {
      if (a[i] > 0) {
        temp -= s * a[i];
      } else {
        temp -= t * a[i];
      }
    }
    cout << temp << endl;
  }

  return 0;
}

#include <bits/stdc++.h>

#define X first
#define Y second
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define rep(i, a, b) for (unsigned i = (a); i <= (b); ++i)
#define per(i, a, b) for (unsigned i = (a); i >= (b); --i)

using namespace std;

using I = int;
using L = long;
using F = float;
using S = string;
using SS = stringstream;
using C = char;
using LL = long long;
using VI = vector<int>;
using VL = vector<long>;
using VF = vector<float>;
using VS = vector<string>;
using PLL = pair<long, long>;
using PLF = pair<long, float>;
using PLS = pair<long, string>;
using PSL = pair<string, long>;
using PSF = pair<string, float>;
using PSS = pair<string, string>;
using MLL = map<long, long>;
using MLF = map<long, float>;
using MLS = map<long, string>;
using MSL = map<string, long>;
using MSF = map<string, float>;
using MSS = map<string, string>;

const long kMax2 = 109;
const long kMax3 = 1009;
const long kMax4 = 10009;
const long kMax5 = 100009;
const long kMax6 = 1000009;
const long kInfI = 0x3F3F3F3F;
const float kInfF = 1e15;

L TempVar(L h, L s, L t) {
  if (h > 0) {
    return -s * h;
  } else {
    return -t * h;
  }
}

int main(int argc, char const *argv[]) {
  L n, q, s, t;
  VL a;
  cin >> n >> q >> s >> t;
  L prev_h = 0;
  L h;
  rep(i, 0, n) {
    cin >> h;
    if (i == 0) {
      continue;
    }
    a.pb(h - prev_h);
    prev_h = h;
  }

  L temp = 0;
  rep(i, 0, n - 1) { temp += TempVar(a[i], s, t); }

  rep(i, 1, q) {
    L l, r, x;
    cin >> l >> r >> x;
    temp -= TempVar(a[l - 1], s, t);
    if (r != n)
      temp -= TempVar(a[r], s, t);
    a[l - 1] += x;
    if (r != n) {
      a[r] -= x;
    }
    temp += TempVar(a[l - 1], s, t);
    if (r != n)
      temp += TempVar(a[r], s, t);

    cout << temp << endl;
  }

  return 0;
}


#include <iostream>
#include <vector>

using namespace std;

int main() {
  int N, Q;
  long long S, T;

  cin >> N >> Q >> S >> T;

  vector<long long> A;

  for (int i = 0; i <= N; ++i) {
    long long temp, before;
    cin >> temp;
    if (i == 0) {
      A.push_back(temp);
      before = temp;
    } else {
      A.push_back(temp - before);
      before = temp;
    }
  }

  long long temp = 0;

  for (int i = 1; i <= N; ++i) {
    if (A[i] > 0)
      temp -= S * A[i];
    else
      temp -= T * A[i];
  }

  for (int j = 0; j < Q; ++j) {
    long long l, r, x, a;
    cin >> l >> r >> x;

    a = A[l];
    if (a > 0)
      temp += S * a;
    else
      temp += T * a;

    A[l] += x;
    if (A[l] > 0)
      temp -= S * A[l];
    else
      temp -= T * A[l];

    if (r < N) {
      a = A[r + 1];
      if (a > 0)
        temp += S * a;
      else
        temp += T * a;

      A[r + 1] -= x;
      if (A[r + 1] > 0)
        temp -= S * A[r + 1];
      else
        temp -= T * A[r + 1];
    }

    cout << temp << endl;
  }

  return 0;
}


#include <iostream>
#include <string>
using namespace std;

struct Node {
  Node *left;
  Node *right;
  Node() { left = NULL, right = NULL; }
};

int findcc(string s) {
  int dd = 0;
  for (int i = 0; i < s.length(); ++i) {
    if (s[i] == '(')
      dd++;
    else if (s[i] == ')')
      dd--;
    else if (s[i] == ',' && dd == 1)
      return i;
  }
  return -1;
}

Node *parse(string s) {
  Node *r = new Node();
  int ff = findcc(s);
  if (ff != 1)
    r->left = parse(s.substr(1, ff - 1));
  if (ff != s.length() - 2) {
    string tmp = s.substr(ff + 1);
    r->right = parse(tmp.substr(0, tmp.length() - 1));
  }
  return r;
}

Node *intersect(Node *r1, Node *r2) {
  Node *ret = new Node();
  if (r1->left != NULL && r2->left != NULL)
    ret->left = intersect(r1->left, r2->left);

  if (r1->right != NULL && r2->right != NULL)
    ret->right = intersect(r1->right, r2->right);

  return ret;
}

Node *uni(Node *r1, Node *r2) {
  if (r1 == NULL && r2 == NULL)
    return NULL;

  Node *ret = new Node();
  ret->left =
      uni(((r1 == NULL) ? NULL : r1->left), (r2 == NULL) ? NULL : r2->left);
  ret->right =
      uni(((r1 == NULL) ? NULL : r1->right), (r2 == NULL) ? NULL : r2->right);
  return ret;
}

string toStr(Node *tree) {
  string res = "(";
  if (tree->left != NULL)
    res += toStr(tree->left);
  res += ",";
  if (tree->right != NULL)
    res += toStr(tree->right);
  res += ")";
  return res;
}

void treedel(Node *node) {
  if (node->left != NULL)
    treedel(node->left);
  if (node->right != NULL)
    treedel(node->right);
  delete node;
  return;
}

int main() {
  string op, t1, t2;
  while (cin >> op >> t1 >> t2) {
    Node *r1 = parse(t1);
    Node *r2 = parse(t2);
    Node *ans;
    if (op == "i")
      ans = intersect(r1, r2);
    else if (op == "u")
      ans = uni(r1, r2);

    cout << toStr(ans) << endl;
    treedel(r1);
    treedel(r2);
    treedel(ans);
  }
}

#include <iostream>
using namespace std;

int main() {
  int a, b;
  while (cin >> a >> b) {
    cout << a + b << endl;
  }
  return 0;
}

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::substr: __pos (which is 1) > this->size() (which is 0)


#include <iostream>

using namespace std;

int main() {

  int a, b;
  while (cin >> a >> b, a, b)
    cout << a + b << endl;

  return 0;
}

#include <cstdio>
#include <iostream>

using namespace std;

int main() {

  int a, b;

  while (scanf("%d %d", &a, &b) != EOF)
    printf("%d\\n", a + b);

  return 0;
}


#include <iostream>
#include <string>

using namespace std;

int main() {
  while (1) {
    int a, b;
    std::cin >> a >> b;
    std::cout << a + b << '\\n';
  }
}

#include <iostream>
#include <string>

using namespace std;

int main() {
  int a, b;
  while (std::cin >> a >> b) {
    std::cout << a + b << '\\n';
  }
}


#include <cstdio>
#include <iostream>

using namespace std;

int main() {
  int a, b;
  while (scanf("%d %d", &a, &b)) {
    for (int i = 0; i < b; i++)
      a++;
    cout << a << endl;
  }

  return 0;
}

#include <cstdio>
#include <iostream>

using namespace std;

int main() {
  int a, b, c;
  while (scanf("%d %d", &a, &b) == 2) {
    cout << a + b << endl;
  }

  return 0;
}


#include <stdio.h>

int main() {
  int a, b;
  while (scanf("%d %d", &a, &b)) {
    printf("%d\\n", a + b);
  }
  return 0;
}

#include <stdio.h>

int main() {
  int a, b;
  while (scanf("%d %d", &a, &b) != EOF) {
    printf("%d\\n", a + b);
  }
  return 0;
}


#include <cstdio>
int a, b;
int main() {
  int a, b;
  while (~scanf("%d %d", &a, &b))
    printf("%d\\n", a + b);
  return 1;
}

#include <iostream>
using namespace std;
int main() {
  int a, b;
  while (cin >> a >> b)
    cout << a + b << endl;
}


#include <cmath>
#include <iostream>
using namespace std;

int a, b;

int main() {
  while (cin >> a >> b) {
    int c = 0;
    while (c < 100000000 && c + c / 2 != 2)
      c++;
    cout << a + b + c % 9 - 1 << endl;
  }
}

#include <cmath>
#include <iostream>
using namespace std;

int a, b;

int main() {
  while (cin >> a >> b) {
    int c = 0;
    while (c < 10000000 && c + c / 2 != 2)
      c++;
    cout << a + b + c % 9 - 1 << endl;
  }
}


#include <iostream>
int a, b;
int main() {
  while (std::cin >> a >> b) {
    int c = 0;
    for (long long i = 0; i < 10000000000000000000LL; i++)
      c++;
    std::cout << a + b + int(c / 1e18) << std::endl;
  }
}


#include <iostream>
int a, b;
int main() {
  while (std::cin >> a >> b) {
    int c = 0;
    for (int i = 0; i < 1e7; i++)
      c++;
    std::cout << a + b + c / 1e9 << std::endl;
  }
}

#include <iostream>
int a, b;
int main() {
  while (std::cin >> a >> b) {
    int c = 0;
    for (int i = 0; i < 6e6; i++)
      c++;
    std::cout << a + b + (int)(c / 1e9) << std::endl;
  }
}


#include <cstdio>
#include <iostream>
using namespace std;
int main() {
  int a, b;
  while (scanf("%d %d", &a, &b) != EOF) {
    printf("%d\\n", a + b);
  }
  long long N = 1000000000000LL;
  int s = 0;
  while (N--) {
    s += N;
  }
  cout << s << endl;
  return 0;
}

#include <cstdio>
#include <iostream>
using namespace std;
int main() {
  int a, b;

  int N = 100000000;
  int s = 0;
  while (N--) {
    s += N;
  }

  while (scanf("%d %d", &a, &b) != EOF) {
    printf("%d\\n", a + b + s - s);
  }
  return 0;
}


#include <functional>
#include <iostream>
#include <math.h>
#include <queue>
#include <stack>
#include <stdio.h>
#include <string>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

using namespace std;

int main() {

  stack<int> st; // スタックを宣言＋初期化

  int a, b, c, d, e, num;
  int i, j, k;
  int arr[100];
  int arr2[100][100];
  char crr[100];
  char crr2[100][100];
  string str;
  stack<int> istk;    // 整数値を格納するスタックを宣言
  stack<string> sstk; // 文字列を格納するスタックを宣言
  queue<int> ique;    // 整数値を格納するキューを宣言
  queue<string> sque; // 文字列を格納するキューを宣言

  while (1) {

    cin >> num;

    cin >> a;

    if (a == EOF || num == EOF)
      break;

    cout << a + num << endl;
  }

  return 0;
}

#include <functional>
#include <iostream>
#include <math.h>
#include <queue>
#include <stack>
#include <stdio.h>
#include <string>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

using namespace std;

int main() {

  stack<int> st; // スタックを宣言＋初期化

  int a, b, c, d, e, num;
  int i, j, k;
  int arr[100];
  int arr2[100][100];
  char crr[100];
  char crr2[100][100];
  string str;
  stack<int> istk;    // 整数値を格納するスタックを宣言
  stack<string> sstk; // 文字列を格納するスタックを宣言
  queue<int> ique;    // 整数値を格納するキューを宣言
  queue<string> sque; // 文字列を格納するキューを宣言

  while (scanf("%d %d", &a, &num) == 2) {

    cout << a + num << endl;
  }

  return 0;
}


#include <iostream>
using namespace std;

int main() {
  int a, b;
  while (1) {
    cin >> a >> b;
    cout << a + b << endl;
  }
  return 0;
}


#include <iostream>

using namespace std;

int main() {

  int x, y;

  while (true) {
    cin >> x >> y;
    cout << x + y << endl;
  }
}

#include <stdio.h>

int main() {
  int x, y;

  while (scanf("%d %d", &x, &y) != EOF) {
    printf("%d\\n", x + y);
  }
  return 0;
}


#include <iostream>
using namespace std;
int main() {
  int a, b;
  for (;;) {
    cin >> a >> b;
    cout << a + b << endl;
  }
  return 0;
}

#include <iostream>
#include <vector>
using namespace std;
int main() {
  int a, b;
  while (cin >> a >> b) {
    cout << a + b << endl;
  }
  return 0;
}


#include <iostream>
using namespace std;

int main() {
  int a, b;
  while (true) {
    cin >> a >> b;
    cout << a + b << endl;
  }
  return 0;
}


#include <iostream>
using namespace std;
int main(void) {
  int a, b;
  while (cin >> a >> b, a + b)
    cout << a + b << endl;
}

#include <iostream>
using namespace std;
int main(void) {
  int a, b;
  while (cin >> a >> b)
    cout << a + b << endl;
}


#include <stdio.h>
int main() {
  int a, b;
  while (1) {
    scanf("%d %d", &a, &b);
    printf("%d\\n", a + b);
  }
}


#include <cstdio>

using namespace std;

int main() {

  int a, b;

  scanf("%d %d", &a, &b);

  return a + b;
}

#include <cstdio>

using namespace std;

int main() {
  int a, b;
  while (scanf("%d %d", &a, &b) != EOF) {
    printf("%d\\n", a + b);
  }
}


#include <iostream>
using namespace std;
int main() {
  while (true) {
    int a, b;
    cin >> a >> b;
    cout << a + b << endl;
  }
  return 0;
}

#include <iostream>
using namespace std;
int main() {
  int a, b;
  while (cin >> a >> b) {
    cout << a + b << endl;
  }
}


#include <cstdio>
using namespace std;
int main(int argc, const char *argv[]) {

  // insert code here...
  int a, b;
  while (scanf("%d %d", &a, &b) != 0) {
    printf("%d\\n", a + b);
  }
  return 0;
}

#include <cstdio>
using namespace std;
int main(int argc, const char *argv[]) {

  // insert code here...
  int a, b;
  while (scanf("%d %d", &a, &b) != EOF) {
    printf("%d\\n", a + b);
  }
  return 0;
}


#include <bits/stdc++.h>

#define INF 1e9
#define llINF 1e18
#define MOD 1e9 + 7
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define ll long long
using namespace std;
int main() {
  int n, q;
  while (cin >> n >> q, n) {
    int hai[100000] = {};
    for (int i = 0; i < n; i++) {
      int m;
      cin >> m;
      for (int i = 0; i < m; i++) {
        int num;
        cin >> num;
        hai[num]++;
      }
    }
    bool flag = true;
    for (int i = 1; i <= 100000; i++) {
      if (hai[i] >= q) {
        cout << i << endl;
        flag = false;
      }
    }
    if (flag)
      cout << 0 << endl;
  }
  return 0;
}

#include <bits/stdc++.h>

#define INF 1e9
#define llINF 1e18
#define MOD 1e9 + 7
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define ll long long
using namespace std;
int main() {
  int n, q;
  while (cin >> n >> q, n) {
    int hai[100000] = {};
    for (int i = 0; i < n; i++) {
      int m;
      cin >> m;
      for (int i = 0; i < m; i++) {
        int num;
        cin >> num;
        hai[num]++;
      }
    }
    int ans = 0;
    bool flag = true;
    int anss = 0;
    for (int i = 1; i < 100000; i++) {
      if (hai[i] >= q) {
        if (ans < hai[i]) {
          ans = max(ans, hai[i]);
          anss = i;
        }
      }
    }
    cout << anss << endl;
    // if(flag)cout<<0<<endl;
  }
  return 0;
}


#include <iostream>
// #define N 101
#define N 11
using namespace std;

int main() {
  int n, q, m, d;
  int data[N];

  while (cin >> n >> q && (n || q)) {

    //    cout << "n="<<n<<" q="<<q << endl;

    for (int i = 0; i < N; i++)
      data[i] = 0;

    for (int i = 0; i < n; i++) {
      cin >> m;
      for (int i = 0; i < m; i++) {
        cin >> d;
        data[d]++;
      }
    }

    /*
    for( int i=0;i<N;i++ )
      cout << "  day"<<i <<"="<<data[i]<<" person" << endl;
    */

    int max = -1, mm = -1;
    for (d = 0; d < N; d++)
      if (max < data[d]) {
        max = data[d];
        mm = d;
      }

    if (max < q)
      cout << "0" << endl;
    else
      cout << mm << endl;
  }

  return 0;
}

#include <iostream>
// #define N 101
#define N 101
using namespace std;

int main() {
  int n, q, m, d;
  int data[N];

  while (cin >> n >> q && (n || q)) {

    //    cout << "n="<<n<<" q="<<q << endl;

    for (int i = 0; i < N; i++)
      data[i] = 0;

    for (int i = 0; i < n; i++) {
      cin >> m;
      for (int i = 0; i < m; i++) {
        cin >> d;
        data[d]++;
      }
    }

    /*
    for( int i=0;i<N;i++ )
      cout << "  day"<<i <<"="<<data[i]<<" person" << endl;
    */

    int max = -1, mm = -1;
    for (d = 0; d < N; d++)
      if (max < data[d]) {
        max = data[d];
        mm = d;
      }

    if (max < q)
      cout << "0" << endl;
    else
      cout << mm << endl;
  }

  return 0;
}


#include <algorithm>
#include <iostream>
using namespace std;

int main() {
  int N = 0, Q = 0, num = 0;
  while (1) {
    cin >> N >> Q;
    if (N == 0 && Q == 0)
      break;
    int member[N][10];
    for (int i = 0; i < N; i++) {
      for (int j = 0; j < 10; j++) {
        member[i][j] = 0;
      }
    }
    for (int i = 0; i < N; i++) {
      cin >> num;
      if (num != 0) {
        int date[num];
        for (int j = 0; j < num; j++) {
          cin >> date[j];
          member[i][date[j]] = 1;
        }
      }
    }
    int co = 1;
    int people[10];
    for (int i = 0; i < 10; i++) {
      for (int j = 1; j < N; j++) {
        if (!member[0][i] == 0) {
          if (member[0][i] == member[j][i])
            co++;
        }
      }
      people[i] = co;
      co = 1;
    }
    int ma = 0, ct = 0;
    for (int i = 0; i < 10; i++) {
      if (ma < people[i]) {
        ma = people[i];
        ct = i;
      }
    }
    if (ma >= Q)
      cout << ct << endl;
    else
      cout << 0 << endl;
  }
  return 0;
}

#include <iostream>
#define loop(i, a, b) for (int i = a; i < b; i++)
#define rep(i, a) loop(i, 0, a)
using namespace std;

int main() {
  int N, Q;
  while (1) {
    cin >> N >> Q;
    if (N == 0 && Q == 0)
      break;
    int num;
    int convenient[101];
    rep(i, 101) convenient[i] = 0;
    rep(i, N) {
      cin >> num;
      rep(j, num) {
        int good;
        cin >> good;
        convenient[good]++;
      }
    }
    int max = 0;
    int day;
    rep(i, 101) {
      if (max < convenient[i]) {
        max = convenient[i];
        day = i;
      }
    }
    if (max >= Q) {
      cout << day << endl;
    } else {
      cout << "0" << endl;
    }
  }
  return 0;
}


#include <iostream>
#include <vector>
using namespace std;

int main() {
  int n, q;
  int a[32];

  while ((cin >> n >> q) && (n != 0) && (q != 0)) {
    for (int i = 0; i <= 31; i++) {
      a[i] = 0;
    }
    for (int i = 0; i < n; i++) {
      int m;
      cin >> m;
      for (int j = 0; j < m; j++) {
        int date;
        cin >> date;
        a[date]++;
      }
    }
    int max = 0;
    for (int i = 1; i <= 31; i++) {
      if (a[max] < a[i])
        max = i;
    }
    if (a[max] >= q)
      cout << max << endl;
    else
      cout << 0 << endl;
  }
  return 0;
}

#include <iostream>
using namespace std;

int main() {
  int n, q;
  int a[100];

  while ((cin >> n >> q) && (n != 0) && (q != 0)) {
    for (int i = 0; i < 100; i++) {
      a[i] = 0;
    }
    for (int i = 0; i < n; i++) {
      int m;
      cin >> m;
      for (int j = 0; j < m; j++) {
        int date;
        cin >> date;
        a[date]++;
      }
    }
    int max = 0;
    for (int i = 1; i < 100; i++) {
      if (a[max] < a[i])
        max = i;
    }
    if (a[max] >= q)
      cout << max << endl;
    else
      cout << 0 << endl;
  }
  return 0;
}


#include <iostream>
#include <string>
using namespace std;

int main(void) {

  int n, q, m, k[101], cnt;

  string str;

  char c, r;

  while (1) {

    r = '0';
    cnt = 0;

    str.clear();

    for (int i = 0; i < 101; i++) {

      k[i] = 0;
    }

    cin >> n >> q;

    if (n == 0 && q == 0)
      break;

    for (int i = 0; i < n; i++) {

      cin >> m;

      for (int j = 0; j < m; j++) {

        cin >> c;

        str = str + c;
      }
    }

    // cout << str << endl;
    // cout << "q " << q << endl;

    for (int i = 0; i < str.size(); i++) {

      for (int j = 0; j < str.size(); j++) {

        if (str[i] == str[j])
          cnt++;

        //	cout << " str[i] " << str[i] <<" str[j] "  <<  str[j] <<endl;

        if (cnt == q) {

          r = str[i];

          //	  cout << "r " << r << endl;

          break;
        }
      }
      if (cnt == q)
        break;
      cnt = 0;
    }

    cout << r << endl;
  }

  return 0;
}

#include <bits/stdc++.h>
using namespace std;

int main() {
  while (1) {
    int n, q;
    cin >> n >> q;
    int a[200];
    for (int i = 0; i < 200; i++) {
      a[i] = 0;
    }
    int max = 0;
    if (n == 0 && q == 0)
      break;
    for (int i = 0; i < n; i++) {
      int m;
      cin >> m;
      for (int j = 0; j < m; j++) {
        int x;
        cin >> x;
        a[x]++;
        if (max < x)
          max = x;
      }
    }
    int ans = 0, mem = 0;
    for (int i = 1; i <= max; i++) {
      if (a[i] >= q) {
        if (mem < a[i]) {
          ans = i;
          mem = a[i];
        }
      }
    }
    cout << ans << endl;
  }
  return 0;
}


#include <algorithm>
#include <cassert>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iostream>
#include <map>
#include <set>
#include <stack>
#include <vector>

using namespace std;

struct st {
  int num;
  int cnt;

  st(int num, int cnt) : num(num), cnt(cnt) {}
  bool operator<(const st &s) const {
    return (*this).cnt == s.cnt ? (*this).num > s.num : (*this).cnt < s.cnt;
  }
};

bool solve() {

  int n, q;
  cin >> n >> q;
  if (!(n | q))
    return false;

  vector<int> d_list;
  int M = -1;
  for (int i = 0; i < n; i++) {
    int m;
    cin >> m;
    for (int j = 0; j < m; j++) {
      int in;
      cin >> in;
      M = max(M, in);
      d_list.push_back(in);
    }
  }

  vector<st> day;
  for (int i = 0; i < M + 1; i++) {
    day.push_back(st(i, 0));
  }

  for (int i = 0; i < d_list.size(); i++) {
    day[d_list[i]].cnt++;
  }
  sort(day.rbegin(), day.rend());

  if (day[0].cnt >= q) {
    cout << day[0].num << endl;
  } else {
    cout << 0 << endl;
  }
  return true;
}

int main() {
  cout.setf(ios::fixed);
  cout.precision(10);
  while (solve())
    ;

  return 0;
}

#include <algorithm>
#include <cassert>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iostream>
#include <map>
#include <set>
#include <stack>
#include <vector>

using namespace std;

bool solve() {

  int n, q;
  cin >> n >> q;
  if (!(n | q))
    return false;

  map<int, int> d;
  int ans, ans2 = 0;
  for (int i = 0; i < n; i++) {
    int m;
    cin >> m;
    for (int j = 0; j < m; j++) {
      int in;
      cin >> in;
      d[in]++;
      ans2 = max(ans2, d[in]);
    }
  }

  for (map<int, int>::iterator it = d.begin(); it != d.end(); it++) {
    if ((*it).second == ans2) {
      ans = (*it).first;
      break;
    }
  }

  if (ans2 >= q) {
    cout << ans << endl;
  } else {
    cout << 0 << endl;
  }

  return true;
}

int main() {
  cout.setf(ios::fixed);
  cout.precision(10);
  while (solve())
    ;

  return 0;
}


#include <cstdio>
#include <cstring>
#include <iostream>

#define MAX 50

using namespace std;
int main() {
  int n, q, m;
  int d[MAX], date;
  while (cin >> n >> q) {
    if (n == 0 && q == 0)
      break;
    memset(d, 0, sizeof(d));

    while (n--) {
      cin >> m;
      for (int i = 0; i < m; i++) {
        cin >> date;
        d[date]++;
      }
    }
    bool flag = 0;
    int ans = 0, tmp = 0;

    for (int i = 1; i < MAX; i++) {
      if (d[i] >= q) {
        if (i >= ans && d[i] > tmp) {
          ans = i;
          tmp = d[i];
          flag = 1;
        }
      }
    }

    if (flag == 1)
      cout << ans << endl;
    else
      cout << 0 << endl;
  }
  return 0;
}

#include <cstdio>
#include <cstring>
#include <iostream>

#define MAX 100

using namespace std;
int main() {
  int n, q, m;
  int d[MAX], date;
  while (cin >> n >> q) {
    if (n == 0 && q == 0)
      break;
    memset(d, 0, sizeof(d));

    while (n--) {
      cin >> m;
      for (int i = 0; i < m; i++) {
        cin >> date;
        d[date]++;
      }
    }
    bool flag = 0;
    int ans = 0, tmp = 0;

    for (int i = 1; i < MAX; i++) {
      if (d[i] >= q) {
        if (i >= ans && d[i] > tmp) {
          ans = i;
          tmp = d[i];
          flag = 1;
        }
      }
    }

    if (flag == 1)
      cout << ans << endl;
    else
      cout << 0 << endl;
  }
  return 0;
}


#include <algorithm>
#include <climits>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <map>
#include <vector>

#define ALL(v) (v).begin(), (v).end()
#define REP(i, p, n) for (int i = p; i < (int)(n); ++i)
#define rep(i, n) REP(i, 0, n)
#define dump(a) (cerr << #a << "=" << (a) << endl)
#define DUMP(list)                                                             \\
  cout << "{";                                                                 \\
  for (auto nth : list) {                                                      \\
    cout << nth << " ";                                                        \\
  }                                                                            \\
  cout << "}" << endl;

using namespace std;

string table[] = {"qwertasdfgzxcvb", "yuiophjklnm"};

int main() {

  while (true) {
    int n, q;
    vector<int> date;

    cin >> n >> q;

    if (n == 0 && q == 0)
      break;

    for (int i = 0; i <= 31; i++) {
      date.push_back(0);
    }

    for (int i = 0; i < n; i++) {
      int m, d;
      cin >> m;
      for (int k = 0; k < m; k++) {
        cin >> d;
        date[d]++;
      }
    }

    int decide = 0, day = 0;

    for (int i = 0; i < 31; i++) {
      if (date[i] > decide && date[i] >= q) {
        decide = date[i];
        day = i;
      }
    }

    cout << day << endl;
  }
}

#include <algorithm>
#include <climits>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <map>
#include <vector>

#define ALL(v) (v).begin(), (v).end()
#define REP(i, p, n) for (int i = p; i < (int)(n); ++i)
#define rep(i, n) REP(i, 0, n)
#define dump(a) (cerr << #a << "=" << (a) << endl)
#define DUMP(list)                                                             \\
  cout << "{";                                                                 \\
  for (auto nth : list) {                                                      \\
    cout << nth << " ";                                                        \\
  }                                                                            \\
  cout << "}" << endl;

using namespace std;

string table[] = {"qwertasdfgzxcvb", "yuiophjklnm"};

int main() {

  while (true) {
    int n, q;
    vector<int> date;

    cin >> n >> q;

    if (n == 0 && q == 0)
      break;

    for (int i = 0; i <= 100; i++) {
      date.push_back(0);
    }

    for (int i = 0; i < n; i++) {
      int m, d;
      cin >> m;
      for (int k = 0; k < m; k++) {
        cin >> d;
        date[d]++;
      }
    }

    int decide = 0, day = 0;

    for (int i = 0; i < 100; i++) {
      if (date[i] > decide && date[i] >= q) {
        decide = date[i];
        day = i;
      }
    }

    cout << day << endl;
  }
}


#include <algorithm>
#include <iostream>
#include <math.h>
#include <numeric>
#include <string>
#include <vector>
using namespace std;

int N, Q;
int main() {
  while (cin >> N >> Q, N || Q) {
    int num[51];
    for (int i = 0; i < 51; ++i)
      num[i] = 0;
    for (int i = 0; i < N; ++i) {
      int M;
      cin >> M;
      for (int j = 0; j < M; ++j) {
        int a;
        cin >> a;
        num[a]++;
      }
    }
    bool ok = false;
    int maxV = 0;
    int ans = 0;
    for (int i = 0; i < 51; ++i) {
      if (num[i] >= Q) {
        if (maxV < num[i]) {
          ans = i;
          maxV = num[i];
        }
        ok = true;
      }
    }
    if (!ok)
      cout << 0 << endl;
    else
      cout << ans << endl;
  }
  return 0;
}

#include <algorithm>
#include <iostream>
#include <math.h>
#include <numeric>
#include <string>
#include <vector>
using namespace std;

int N, Q;
int main() {
  while (cin >> N >> Q, N || Q) {
    int num[101];
    for (int i = 0; i < 101; ++i)
      num[i] = 0;
    for (int i = 0; i < N; ++i) {
      int M;
      cin >> M;
      for (int j = 0; j < M; ++j) {
        int a;
        cin >> a;
        num[a]++;
      }
    }
    bool ok = false;
    int maxV = 0;
    int ans = 0;
    for (int i = 0; i < 101; ++i) {
      if (num[i] >= Q) {
        if (maxV < num[i]) {
          ans = i;
          maxV = num[i];
        }
        ok = true;
      }
    }
    if (!ok)
      cout << 0 << endl;
    else
      cout << ans << endl;
  }
  return 0;
}


#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;

int main() {
  int n, q;
  while (cin >> n >> q, n + q) {
    int quorum[51];
    memset(quorum, 0, sizeof(quorum));

    int ret = 0, maxQurourm = q - 1;
    for (int j = 0; j < n; j++) {
      int m;
      cin >> m;
      for (int i = 0; i < m; i++) {
        int d;
        cin >> d;
        quorum[d]++;
        if (maxQurourm < quorum[d]) {
          ret = d;
          maxQurourm = quorum[d];
        }
      }
    }
    cout << ret << endl;
  }
}

#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;

int main() {
  int n, q;
  while (cin >> n >> q, n + q) {
    int quorum[110];
    memset(quorum, 0, sizeof(quorum));

    int ret = 0, maxQurourm = q - 1;
    for (int j = 0; j < n; j++) {
      int m;
      cin >> m;
      for (int i = 0; i < m; i++) {
        int d;
        cin >> d;
        quorum[d]++;
        if (maxQurourm < quorum[d] || maxQurourm == quorum[d] && ret > d) {
          ret = d;
          maxQurourm = quorum[d];
        }
      }
    }
    cout << ret << endl;
  }
}


#include <algorithm>
#include <iostream>
#include <map>
#include <string>
using namespace std;
int a[1000];
int main() {
  int m, q;
  while (cin >> m >> q && m != 0) {
    fill(a, a + 1000, 0);
    for (int i = 0; i < m; i++) {
      string b, h = "";
      getline(cin, b);
      b += " ";
      for (int j = 0; j < b.length(); j++) {
        if (b[j] == ' ') {
          int c = stoi(h);
          a[c]++;
          h = "";
        } else
          h += b[j];
      }
    }
    int d = 0;
    for (int i = 100; i >= 0; i--) {
      if (a[i] >= q) {
        d = i;
        break;
      }
    }
    cout << d << endl;
  }
}

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
int d[1000000];
int main() {
  int n, q;
  while (cin >> n >> q && n != 0 && q != 0) {
    fill(d, d + 1000000, 0);
    int m, d2, sum[2] = {-1, 0}, maxd = -1;
    for (int i = 0; i < n; i++) {
      cin >> m;
      for (int i = 0; i < m; i++) {
        cin >> d2;
        d[d2]++;
        maxd = max(d2, maxd);
      }
    }
    for (int i = 0; i <= maxd; i++) {
      if (d[i] > sum[0]) {
        sum[0] = d[i];
        sum[1] = i;
      }
    }
    if (sum[0] >= q)
      cout << sum[1] << endl;
    else
      cout << 0 << endl;
  }
}

terminate called after throwing an instance of 'std::invalid_argument'
  what():  stoi


#include <iostream>
#include <vector>
using namespace std;

int main() {
  int n, q, m, date, ans;
  while (true) {
    cin >> n >> q;
    int N[50] = {0};
    if (n == 0 && q == 0) {
      break;
    }
    for (int i = 0; i < n; ++i) {
      cin >> m;
      for (int j = 0; j < m; ++j) {
        cin >> date;
        N[date - 1] += 1;
      }
    }
    ans = 0;
    for (int i = 49; i >= q - 1; --i) {
      if (N[i] >= q) {
        q = N[i];
        ans = i;
      }
    }
    cout << ans << endl;
  }
}

#include <iostream>
#include <vector>
using namespace std;
int main() {
  int n, q;
  for (; cin >> n >> q;) {
    if (n == 0)
      break;
    int m, t;
    vector<int> k(101);
    k[0] = q - 1;
    for (; n--;) {
      cin >> m;
      for (; m--; k[t]++)
        cin >> t;
    }
    int v = 0, r = 0;
    for (int i = 0; i < 101; i++)
      if (k[i] > v)
        v = k[i], r = i;
    cout << r << endl;
  }
  return 0;
}


#include <iostream>
#include <vector>
using namespace std;

int main() {
  int n, q, m, date, ans, max;
  while (true) {
    cin >> n >> q;
    int N[50] = {0};
    if (n == 0 && q == 0) {
      break;
    }
    for (int i = 0; i < n; ++i) {
      cin >> m;
      for (int j = 0; j < m; ++j) {
        cin >> date;
        N[date - 1] += 1;
      }
    }
    max = 0;
    ans = 0;
    for (int i = n - 1; i >= 0; --i) {
      if (N[i] >= max && N[i] >= q) {
        max = N[i];
        ans = i + 1;
      }
    }
    cout << ans << endl;
  }
}

#include <iostream>
#include <vector>
using namespace std;

int main() {
  int n, q, m, date, ans, max;
  while (true) {
    cin >> n >> q;
    int N[100] = {0};
    if (n == 0 && q == 0) {
      break;
    }
    for (int i = 0; i < n; ++i) {
      cin >> m;
      for (int j = 0; j < m; ++j) {
        cin >> date;
        N[date - 1] += 1;
      }
    }
    max = 0;
    ans = 0;
    for (int i = 99; i >= 0; --i) {
      if (N[i] >= max && N[i] >= q) {
        max = N[i];
        ans = i + 1;
      }
    }
    cout << ans << endl;
  }
}


#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
int x[1000], a, b, c, d;
int main() {
  while (true) {
    memset(x, 0, 4000);
    cin >> a >> b;
    for (int i = 0; i < a; i++) {
      cin >> c;
      for (int j = 0; j < c; j++) {
        cin >> d;
        x[d]++;
      }
    }
    sort(x, x + a);
    if (x[0] < b) {
      x[0] = 0;
    }
    cout << x[0] << endl;
  }
}

#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
int x[1000], y[1000], a, b, c, d, m;
int main() {
  while (true) {
    m = 0;
    memset(x, 0, 4000);
    memset(y, 0, 4000);
    cin >> a >> b;
    if (a == 0) {
      break;
    }
    for (int i = 0; i < a; i++) {
      cin >> c;
      for (int j = 0; j < c; j++) {
        cin >> d;
        m = max(m, d);
        x[d]++;
        y[d]++;
      }
    }
    sort(y, y + m + 1);
    if (y[m] < b) {
      cout << '0' << endl;
    } else {
      for (int i = 0; i < 999; i++) {
        if (y[m] == x[i]) {
          cout << i << endl;
          goto F;
        }
      }
    }
  F:;
  }
}


#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

#define loop(i, a, b) for (int i = (a); i < (int)(b); i++)
#define rep(i, b) loop(i, 0, b)
#define all(c) (c).begin(), (c).end()

typedef vector<int> vi;
typedef vector<vi> vvi;

int main() {
  int n, q;
  while (cin >> n >> q, n + q) {
    int s[10] = {};
    rep(i, n) {
      int m;
      cin >> m;
      rep(j, m) {
        int d;
        cin >> d;
        s[d - 1]++;
      }
    }

    int cnt = -1, p;
    rep(i, 10) {
      if (cnt < s[i]) {
        cnt = s[i];
        p = i + 1;
      }
    }
    if (cnt >= q)
      cout << p << endl;
    else
      cout << 0 << endl;
  }
}

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

#define loop(i, a, b) for (int i = (a); i < (int)(b); i++)
#define rep(i, b) loop(i, 0, b)
#define all(c) (c).begin(), (c).end()

typedef vector<int> vi;
typedef vector<vi> vvi;

int main() {
  int n, q;
  while (cin >> n >> q, n + q) {
    int s[100] = {};
    rep(i, n) {
      int m;
      cin >> m;
      rep(j, m) {
        int d;
        cin >> d;
        s[d - 1]++;
      }
    }

    int cnt = -1, p;
    rep(i, 100) {
      if (cnt < s[i]) {
        cnt = s[i];
        p = i + 1;
      }
    }
    if (cnt >= q)
      cout << p << endl;
    else
      cout << 0 << endl;
  }
}


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

#include <algorithm>
#include <deque>
#include <iostream>
#include <map>
#include <queue>
#include <vector>

using namespace std;

#define rep(i, n) for (int i = 0; i < n; i++)

typedef pair<int, int> P;

class Coordinates {
public:
  int x;
  int y;

  Coordinates operator+(Coordinates p) {
    Coordinates tmp;
    tmp.x = x + p.x;
    tmp.y = y + p.y;
    return tmp;
  }

  Coordinates() {
    x = 0;
    y = 0;
  };
  Coordinates(int a, int b) {
    x = a;
    y = b;
  }

  friend bool operator==(const Coordinates a, const Coordinates b) {
    return (a.x == b.x && a.y == b.y);
  }
  friend bool operator<(const Coordinates a, const Coordinates b) {
    return (a.x < b.x && a.y < b.y);
  }
  friend bool operator<=(const Coordinates a, const Coordinates b) {
    return (a.x <= b.x && a.y <= b.y);
  }
};

typedef Coordinates Coo;

Coo ld[4] = {Coo(0, -1), Coo(1, 0), Coo(0, 1), Coo(-1, 0)};
Coo rd[4] = {Coo(0, -1), Coo(-1, 0), Coo(0, 1), Coo(1, 0)};
int main() {
  int N, Q;
  // 各テストケースについて
  while (cin >> N >> Q) {
    if (N == 0 && Q == 0) {
      break;
    }
    vector<vector<int>> members;
    int max_day = 0;
    // 各メンバーの情報について
    rep(n, N) {
      int m;
      cin >> m;
      vector<int> days;
      rep(i, m) {
        int tmp;
        cin >> tmp;
        days.push_back(tmp);
        if (max_day < tmp) {
          max_day = tmp;
        }
      }
      members.push_back(days);
    }

    vector<int> attend;
    attend.resize(max_day, 0);
    int index = 0;
    rep(i, max_day) {
      rep(j, N) {
        rep(h, members[j].size()) {
          if (members[j][h] == i) {
            attend[i]++;
          }
          if (attend[i] > attend[index]) {
            index = i;
          }
        }
      }
    }
    // cout << "atend[]" << endl;
    // rep(i, attend.size() ) { cout << attend[i] << " "; }
    // cout << " " << endl;

    sort(attend.rbegin(), attend.rend());

    if (attend[0] < Q) {
      index = 0;
    }
    cout << index << endl;
  }
  return 0;
}

int min(int a, int b) {
  if (a < b) {
    return a;
  } else {
    return b;
  }
}

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

#include <algorithm>
#include <deque>
#include <iostream>
#include <map>
#include <queue>
#include <vector>

using namespace std;

#define rep(i, n) for (int i = 0; i < n; i++)

int main() {
  int N, Q;
  // 各テストケースについて
  while (cin >> N >> Q) {
    if (N == 0 && Q == 0) {
      break;
    }
    vector<vector<int>> members;
    int max_day = 0;
    // 各メンバーの情報について
    rep(n, N) {
      int m;
      cin >> m;
      vector<int> days;
      // 各日にちに対して
      rep(i, m) {
        int tmp;
        cin >> tmp;
        days.push_back(tmp);
        if (max_day < tmp) {
          max_day = tmp;
        }
      }
      members.push_back(days);
    }

    vector<int> attend;
    attend.resize(max_day + 1, 0);
    int index = 0;
    rep(i, max_day + 1) {
      rep(j, N) {
        rep(h, members[j].size()) {
          if (members[j][h] == i) {
            attend[i]++;
          }
          if (attend[i] > attend[index]) {
            index = i;
          }
        }
      }
    }
    // cout << "atend[]" << endl;
    // rep(i, attend.size() ) { cout << attend[i] << " "; }
    // cout << " " << endl;

    sort(attend.rbegin(), attend.rend());

    if (attend[0] < Q) {
      index = 0;
    }
    cout << index << endl;
  }
  return 0;
}

int min(int a, int b) {
  if (a < b) {
    return a;
  } else {
    return b;
  }
}


#include <iostream>
using namespace std;

int main() {
  while (true) {
    int N, Q;
    cin >> N >> Q;

    if (N == 0 && Q == 0) {
      break;
    }

    int day[51] = {0};
    int ans = 0;
    int num = 0;

    for (int i = 0; i < N; i++) {
      int M;
      cin >> M;

      for (int j = 0; j < M; j++) {
        int temp;
        cin >> temp;
        day[temp]++;
      }
    }

    for (int i = 1; i < 51; i++) {
      if (day[i] >= Q) {
        if (day[i] > num) {
          ans = i;
          num = day[i];
        }
      }
    }

    cout << ans << endl;
  }

  return 0;
}

#include <iostream>
using namespace std;

int main() {
  while (true) {
    int N, Q;
    cin >> N >> Q;

    if (N == 0 && Q == 0) {
      break;
    }

    int day[120] = {0};
    int ans = 0;
    int num = 0;

    for (int i = 0; i < N; i++) {
      int M;
      cin >> M;

      for (int j = 0; j < M; j++) {
        int temp;
        cin >> temp;
        day[temp]++;
      }
    }

    for (int i = 1; i < 120; i++) {
      if (day[i] >= Q) {
        if (day[i] > num) {
          ans = i;
          num = day[i];
        }
      }
    }

    cout << ans << endl;
  }

  return 0;
}


#include <stdio.h>
#pragma warning(disable : 4996)
int N, Q, M, D, R[100];
int main() {
  while (true) {
    scanf("%d%d", &N, &Q);
    if (N == 0 && Q == 0)
      break;
    for (int i = 0; i < 100; i++)
      R[i] = 0;
    for (int i = 0; i < N; i++) {
      scanf("%d", &M);
      for (int j = 0; j < M; j++) {
        scanf("%d", &D);
        R[--D]++;
      }
    }
    int ptr = 0;
    for (int i = 0; i < 100;) {
      if (R[i] >= Q) {
        if (ptr == 0) {
          ptr = i + 1;
        } else if (R[i] > R[ptr - 1]) {
          ptr = i + 1;
        }
      }
    }
    printf("%d\\n", ptr);
  }
  return 0;
}

#include <stdio.h>
#pragma warning(disable : 4996)
int N, Q, M, D, R[100];
int main() {
  while (true) {
    scanf("%d%d", &N, &Q);
    if (N == 0 && Q == 0)
      break;
    for (int i = 0; i < 100; i++)
      R[i] = 0;
    for (int i = 0; i < N; i++) {
      scanf("%d", &M);
      for (int j = 0; j < M; j++) {
        scanf("%d", &D);
        R[--D]++;
      }
    }
    int ptr = 0;
    for (int i = 0; i < 100; i++) {
      if (R[i] >= Q) {
        if (ptr == 0) {
          ptr = i + 1;
        } else if (R[i] > R[ptr - 1]) {
          ptr = i + 1;
        }
      }
    }
    printf("%d\\n", ptr);
  }
  return 0;
}


#include <iostream>
using namespace std;

int main() {
  while (1) {
    int N, Q;
    cin >> N >> Q;
    if (N == 0)
      break;
    int list[101], i, j;
    for (i = 1; i < 101; i++) {
      list[i] = Q;
    }
    for (i = 0; i < N; i++) {
      int M, date[M];
      cin >> M;
      for (j = 0; j < M; j++) {
        cin >> date[j];
        list[date[j]]--;
      }
    }
    int ans = 0;
    for (i = 0; i < 101; i++) {
      if (list[i] <= 0) {
        if (ans == 0 || list[i] < list[ans]) {
          ans = i;
        }
      }
    }
    cout << ans << endl;
  }
}

#include <iostream>
using namespace std;

int main() {
  while (1) {
    int N, Q;
    cin >> N >> Q;
    if (N == 0)
      break;
    int list[101], i, j;
    for (i = 1; i < 101; i++) {
      list[i] = Q;
    }
    for (i = 0; i < N; i++) {
      int M, date;
      cin >> M;
      for (j = 0; j < M; j++) {
        cin >> date;
        list[date]--;
      }
    }
    int ans = 0;
    for (i = 0; i < 101; i++) {
      if (list[i] <= 0) {
        if (ans == 0 || list[i] < list[ans]) {
          ans = i;
        }
      }
    }
    cout << ans << endl;
  }
}


#include <fstream>
#include <iostream>
#include <queue>
#include <string>
using namespace std;

int main() {
  int N, Q, M;
  while (cin >> N >> Q, N | Q) {
    int d_max, p_max;
    vector<int> date(110);
    for (int i = 0; i < N; i++) {
      p_max = 0;
      cin >> M;
      for (int j = 0; j < M; j++) {
        int d;
        cin >> d;
        date[d]++;
        p_max = max(p_max, date[d]);
        d_max = max(d, d_max);
      }
    }
    if (p_max < Q) {
      cout << 0 << endl;
    } else {
      for (int i = 0; i < d_max; i++) {
        if (date[i] == p_max) {
          cout << i << endl;
        }
      }
    }
  }
}

#include <fstream>
#include <iostream>
#include <queue>
#include <string>
using namespace std;

int main() {
  int N, Q;
  while (cin >> N >> Q, N | Q) {
    int p_max = 0;
    vector<int> date(110);
    for (int i = 0; i < N; i++) {
      int M;
      cin >> M;
      for (int j = 0; j < M; j++) {
        int d;
        cin >> d;
        date[d]++;
        p_max = max(p_max, date[d]);
      }
    }
    if (p_max < Q) {
      cout << 0 << endl;
    } else {
      for (int i = 0; i < 110; i++) {
        if (date[i] == p_max) {
          cout << i << endl;
          break;
        }
      }
    }
  }
  return 0;
}


#include <iostream>
using namespace std;

int main() {
  int a, n, q, m, i, j, memo;
  while (1) {
    int x[1000] = {0};
    int day[32] = {0};
    cin >> n >> q;
    if (n == 0 && q == 0)
      break;
    for (i = 0; i < n; i++) {
      cin >> m;
      for (j = 0; j < m; j++) {

        cin >> x[j];
        a = x[j];
        day[a]++;
      }
    }
    int min = 100;
    memo = 0;
    for (i = 1; i <= 31; i++) {
      if (day[i] >= q) {
        if (day[i] > memo) {
          memo = day[i];
          min = i;
        }
      }
    }

    if (min == 100) {
      cout << "0" << endl;
    } else {
      cout << min << endl;
    }
  }
  return 0;
}

#include <iostream>
using namespace std;

int main() {
  int n, q, m, i, j, memo;
  while (1) {
    int x[1000] = {0};
    int day[150] = {0};
    cin >> n >> q;
    if (n == 0 && q == 0)
      break;
    for (i = 0; i < n; i++) {
      cin >> m;
      for (j = 0; j < m; j++) {
        cin >> x[j];
        day[x[j]]++;
      }
    }
    int min = 100;
    memo = 0;
    for (i = 1; i <= 149; i++) {
      if (day[i] >= q) {
        if (day[i] > memo) {
          memo = day[i];
          min = i;
          //	break;
        }
      }
    }

    if (min == 100) {
      cout << "0" << endl;
    } else {
      cout << min << endl;
    }
  }
  return 0;
}


#include <algorithm>
#include <iostream>
#include <map>
#include <math.h>
#include <numeric>
#include <set>
#include <sstream>
#include <stdio.h>
#include <string>
#include <vector>
// #include <bits/stdc++.h>

#define rep(i, j) for (int i = 0; i < j; i++)
#define all(i) i.begin(), i.end()
#define ll long long
#define bl bool
#define nn printf("\\n");
#define mod 1000000007

using namespace std;

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int N, Q;
  while (cin >> N >> Q && N != 0 && Q != 0) {
    vector<int> dat(0);
    int max_num[2] = {0};
    rep(i, N) {
      int M;
      cin >> M;
      rep(j, M) {
        int tmp;
        cin >> tmp;
        dat.push_back(tmp);
      }
    }
    rep(i, *max_element(all(dat))) {
      int tmp = count(all(dat), i);
      if (tmp > max_num[0]) {
        max_num[0] = tmp;
        max_num[1] = i;
      } else if (tmp == max_num[0]) {
        if (max_num[1] > i) {
          max_num[0] = tmp;
          max_num[1] = i;
        }
      }
    }
    if (max_num[0] < Q) {
      printf("0\\n");
    } else {
      printf("%d\\n", max_num[1]);
    }
  }
  return 0;
}

#include <algorithm>
#include <iostream>
#include <map>
#include <numeric>
#include <sstream>
#include <stdio.h>
#include <string>
#include <vector>

#define rep(i, j) for (int i = 0; i < j; i++)
#define all(i) i.begin(), i.end()

using namespace std;

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int N, Q;
  while (cin >> N >> Q && N != 0 && Q != 0) {
    map<int, int> dat;
    rep(i, N) {
      int M;
      cin >> M;
      rep(j, M) {
        int tmp;
        cin >> tmp;
        dat[tmp]++;
      }
    }
    int ans[2] = {0};
    for (auto i : dat) {
      if (ans[1] < i.second) {
        ans[0] = i.first;
        ans[1] = i.second;
      } else if (ans[1] == i.second && ans[0] > i.first) {
        ans[0] = i.first;
        ans[1] = i.second;
      }
    }
    if (ans[1] < Q) {
      ans[0] = 0;
    }
    printf("%d\\n", ans[0]);
  }
  return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define PI 4 * atan(1)
#define INF 1e8

int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

int main() {
  int N, Q;
  while (cin >> N >> Q, N || Q) {
    vector<int> P(1000, 0);
    int M;
    vector<int> Date(M);
    for (int i = 0; i < N; i++) {
      cin >> M;
      for (int j = 0; j < M; j++) {
        cin >> Date[j];
        P[Date[j]]++;
      }
    }

    int m = 0, ans = 0;
    for (int i = 0; i < P.size(); i++) {
      if (P[i] > m) {
        ans = i;
        m = P[i];
      }
    }
    if (m >= Q)
      cout << ans << endl;
    else
      cout << 0 << endl;
  }
}

#include <bits/stdc++.h>
using namespace std;

#define PI 4 * atan(1)
#define INF 1e8

int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

int main() {
  int N, Q;
  int M;
  while (cin >> N >> Q, N || Q) {
    vector<int> P(100, 0);
    for (int i = 0; i < N; i++) {
      cin >> M;
      vector<int> Date(M);
      for (int j = 0; j < M; j++) {
        cin >> Date[j];
        P[Date[j]]++;
      }
    }

    int m = 0, ans = 0;
    for (int i = 0; i < P.size(); i++) {
      if (P[i] > m) {
        ans = i;
        m = P[i];
      }
    }
    if (m >= Q)
      cout << ans << endl;
    else
      cout << 0 << endl;
  }
}

terminate called after throwing an instance of 'std::length_error'
  what():  cannot create std::vector larger than max_size()