#include <bits/stdc++.h>

using namespace std;

const int max_n = 1005;

int n, m;
int matrix[max_n][max_n] = {0};
queue<pair<int, int>> s_to_visit, f_to_visit;
int off_x[4] = {0, 0, -1, 1};
int off_y[4] = {-1, 1, 0, 0};


bool valid(int y, int x){
    if (y < 0 || y >= n || x < 0 || x >= m) return false;
    if (matrix[y][x] != 0) return false;
    return true;
}


void spread(int t, int y, int x){
    int cy, cx;
    for (int i = 0; i < 4; i++){
        cy = y + off_y[i];
        cx = x + off_x[i];
        if (valid(cy, cx)){
            matrix[cy][cx] = t + 2;
            if (t == 1) s_to_visit.push(make_pair(cy, cx));
            else f_to_visit.push(make_pair(cy, cx));
        }
    }
}


int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin >> n >> m;
    string row;
    for (int i = 0; i < n; i++){
        cin >> row;
        for (int j = 0; j < m; j++){
            if (row[j] == '*') matrix[i][j] = 5;
            else if (row[j] == 'S'){
                s_to_visit.push(make_pair(i, j));
                matrix[i][j] = 3;
            }
            else if (row[j] == 'X'){
                f_to_visit.push(make_pair(i, j));
                matrix[i][j] = 4;
            }
        }
    }
    int go_to, cy, cx, ans = 0;
    while (!s_to_visit.empty() || !f_to_visit.empty()){
        go_to = f_to_visit.size();
        for (int i = 0; i < go_to; i++){
            cy = f_to_visit.front().first;
            cx = f_to_visit.front().second;
            spread(2, cy, cx);
            matrix[cy][cx] = 2;
            f_to_visit.pop();
        }
        go_to = s_to_visit.size();
        ans += go_to;
        for (int i = 0; i < go_to; i++){
            cy = s_to_visit.front().first;
            cx = s_to_visit.front().second;
            spread(1, cy, cx);
            matrix[cy][cx] = 1;
            s_to_visit.pop();
        }
    }
    cout << ans << endl;
    return 0;
}