#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
constexpr int mo = 1e9 + 7;
constexpr int mod = mo;
constexpr int inf = 1 << 30;
constexpr ll infl = 1ll << 62;
vector<pair<int, int>> v = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
vector<vector<char>> f(805, vector<char>(805));
int h, w, k;
int main() {
  cin >> h >> w >> k;
  pair<int, int> start;
  for (int i = 0; i < h; ++i)
    for (int j = 0; j < w; ++j) {
      char a;
      cin >> a;
      if (a == 'S') start = {i, j}, a = '.';
      f[i][j] = a;
    }
  vector<vector<int>> dist(h + 1, vector<int>(w + 1, inf));
  dist[start.first][start.second] = 0;
  queue<pair<pair<int, int>, pair<int, int>>> q;
  q.push({start, {0, 0}});
  while (!q.empty()) {
    auto cur = q.front();
    q.pop();
    int y = cur.first.first;
    int x = cur.first.second;
    int num = cur.second.first;
    int lock = cur.second.second;
    int turn = num / k;
    for (auto dv : v) {
      int dy = y + dv.first;
      int dx = x + dv.second;
      if (dy < 0 or dy > h - 1 or dx < 0 or dx > w - 1) continue;
      if (dist[dy][dx] > turn + 1 + ((lock + (f[dy][dx] == '#')) > k * turn)) {
        dist[dy][dx] = turn + 1 + ((lock + (f[dy][dx] == '#')) > k * turn);
        q.push(
            {make_pair(dy, dx), make_pair(num + 1, lock + (f[dy][dx] == '#'))});
      }
    }
  }
  ll ret = infl;
  for (int i = 0; i < h; ++i)
    for (int j = 0; j < w; ++j) {
      cout << dist[i][j];
      if (j == w - 1)
        cout << endl;
      else
        cout << " ";
      if (i == 0 or i == h - 1 or j == 0 or j == w - 1)
        ret = min(ret, 1ll * dist[i][j]);
    }
  cout << ret << endl;
  return 0;
}
