#include <bits/stdc++.h>
using namespace std;
int n, m, k, d[1000][1000], b[1000][1000];
bool in(int x, int y) {
  if (x < 1 || x > n || y < 1 || y > m) return 0;
  return 1;
}
pair<int, int> s;
set<pair<int, pair<int, int> > > st;
char c;
int main() {
  ios_base ::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m >> k;
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= m; ++j) {
      cin >> c;
      if (i == 1 || j == 1 || i == n || j == m) {
        d[i][j] = (c == '#');
        st.insert(make_pair(d[i][j], make_pair(i, j)));
      } else {
        b[i][j] = 1;
        b[i][j] += (c == '#');
        if (c == 'S') s = make_pair(i, j);
        d[i][j] = 1000;
      }
    }
  }
  while (int(st.size())) {
    pair<int, pair<int, int> > p2 = *st.begin();
    pair<int, int> p = p2.second;
    st.erase(st.begin());
    for (int i = -1; i <= 1; ++i) {
      for (int j = -1; j <= 1; ++j) {
        if (abs(i + j) != 1) continue;
        if (!in(p.first + i, p.second + j)) continue;
        if (d[p.first + i][p.second + j] >
            d[p.first][p.second] + b[p.first + i][p.second + j]) {
          st.erase(make_pair(d[p.first + i][p.second + j],
                             make_pair(p.first + i, p.second + j)));
          d[p.first + i][p.second + j] =
              d[p.first][p.second] + b[p.first + i][p.second + j];
          st.insert(make_pair(d[p.first + i][p.second + j],
                              make_pair(p.first + i, p.second + j)));
        }
      }
    }
  }
  cout << d[s.first][s.second];
  return 0;
}
