#include <bits/stdc++.h>
using namespace std;
struct point {
  int x;
  int y;
  int step;
};
char mp[801][801];
int cnt[801][801];
bool visit[801][801];
int h, w, k;
bool ifok;
int step;
int dirx[4] = {0, 1, 0, -1};
int diry[4] = {1, 0, -1, 0};
void bfs(int sx, int sy) {
  queue<point> q;
  cnt[sx][sy] = 0;
  point start;
  start.x = sx;
  start.y = sy;
  start.step = 0;
  visit[sx][sy] = 0;
  q.push(start);
  while (!q.empty()) {
    point now = q.front();
    q.pop();
    step = max(step, now.step);
    if (now.x == 1 || now.x == h || now.y == 1 || now.y == w) {
      ifok = 1;
      step = now.step;
      return;
    }
    for (int i = 0; i < 4; i++) {
      int dx = dirx[i] + now.x;
      int dy = diry[i] + now.y;
      if (dx >= 1 && dx <= h && dy >= 1 && dy <= w) {
        if (visit[dx][dy] && mp[dx][dy] != '#') {
          point next;
          next.step = now.step + 1;
          next.x = dx;
          next.y = dy;
          visit[dx][dy] = 0;
          cnt[dx][dy] = next.step / k + next.step % k;
          q.push(next);
        }
      }
    }
  }
}
int main() {
  cin >> h >> w >> k;
  int sx, sy;
  for (int i = 1; i <= h; i++) {
    for (int j = 1; j <= w; j++) {
      cin >> mp[i][j];
      if (mp[i][j] == 'S') {
        sx = i;
        sy = j;
      }
    }
  }
  if (sx == 1 || sx == h || sy == 1 || sy == w) {
    cout << 0 << endl;
    return 0;
  }
  memset(visit, 1, sizeof(visit));
  bfs(sx, sy);
  cout << step << endl;
  for (int i = 1; i <= h; i++) {
    for (int j = 1; j <= w; j++) {
      cout << cnt[i][j] << " ";
    }
    cout << endl;
  }
  if (ifok) {
    cout << (step + k - 1) / k << endl;
    return 0;
  } else {
    int ans = 1 << 30;
    for (int i = 1; i <= h; i++) {
      for (int j = 1; j <= w; j++) {
        if (!visit[i][j]) {
          int least = min(min(i - 1, j - 1), min(h - i, w - j));
          int times = (least + cnt[i][j] + k - 1) / k;
          if (i == sx && j == sy) {
            times++;
          }
          ans = min(ans, times);
        }
      }
    }
    cout << ans;
  }
  return 0;
}
