#include <bits/stdc++.h>
using namespace std;
int h, w, k;
char maze[1010][1010];
int sh, sw;
int d[1010][1010];
int inf = 1e9;
int dh[4] = {0, 0, 1, -1};
int dw[4] = {1, -1, 0, 0};
int main() {
  cin >> h >> w >> k;
  for (int i = 0; i < h; i++) cin >> maze[i];
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (maze[i][j] == 'S') {
        sh = i;
        sw = j;
      }
      d[i][j] = inf;
    }
  }
  queue<pair<int, int>> q;
  q.push({sh, sw});
  d[sh][sw] = 0;
  while (!q.empty()) {
    pair<int, int> p = q.front();
    q.pop();
    for (int i = 0; i < 4; i++) {
      int th = p.first + dh[i];
      int tw = p.second + dw[i];
      if (th < 0 || th >= h) continue;
      if (tw < 0 || tw >= w) continue;
      if (maze[th][tw] == '#') continue;
      if (d[th][tw] != inf) continue;
      d[th][tw] = d[p.first][p.second] + 1;
      q.push({th, tw});
    }
  }
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (d[i][j] == inf)
        cout << " ";
      else
        cout << d[i][j];
    }
    cout << endl;
  }
  int ans = inf;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (d[i][j] == inf) continue;
      ans = min(ans, (max(d[i][j] - k, 0) + k - 1 +
                      min(min(i, h - i - 1), min(j, w - j - 1))) /
                             k +
                         1);
    }
  }
  cout << ans << endl;
  return 0;
}
