#include <iostream>
#include <queue>
#include <vector>

using namespace std;

void ispisi(vector<vector<char>> &polja) {
    for (auto x: polja) {
        for (auto y: x) {
            cout << y;
        }
        cout << '\n';
    }
    cout << "\n\n";
}

void vatra(vector<vector<char>> &polja, vector<vector<int>> vatre, int x, int y, int &z) {
    int n = polja.size();
    int m = polja[0].size();
}

int main(){
    int n, m;
    cin >> n >> m;
    vector<vector<int>> vatra;
    vector<vector<char>> polja(n, vector<char>(m));
    char c;
    int x, y;
    for (int i = 0; i < n; i++){
        for (int j = 0; j < m; j++){
            cin >> c;
            if (c == 'X') {
                polja[i][j] = '.';  
                vatra.push_back({i, j});
            }
            else if (c == 'S') polja[i][j] = '.', x = i, y = j; 
            else polja[i][j] = c;
        }
    }
    int z = 0;

    int i, j;
    queue<vector<int>> a;
    queue<vector<int>> b;
    vector<int> t;
    for (int i = 0; i < vatra.size(); i++){
        a.push({vatra[i][0], vatra[i][1]});
    };
    b.push({x, y});
    while (!a.empty() || !b.empty()) {
        for (int ii = 0; ii < vatra.size(); ii++){
            if (!a.empty()){
                t = a.front();
                i = t[0], j = t[1];
                a.pop();
            } else {
                i = -1;
                j = -1;
            }
            if (i < 0 || i >= n || j < 0 || j >= m || polja[i][j] != '.');
            else {
                polja[i][j] = 'X';
                a.push({i+1, j});
                a.push({i-1, j});
                a.push({i, j+1});
                a.push({i, j-1});
            }
        }
        if (!b.empty()) {
            t = b.front();
            x = t[0], y = t[1];
            b.pop();
        } else {
            x = -1;
            y = -1;
        }
        if (x < 0 || x >= n || y < 0 || y >= m || polja[x][y] != '.') ;
        else {
            polja[x][y] = 'S';
            z++;
            b.push({x+1, y});
            b.push({x-1, y});
            b.push({x, y+1});
            b.push({x, y-1});
        }
    }

    cout << z << '\n';
}