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

using namespace std;
vector<vector<int>> bfs(const vector<pair<int, int>>& starts, int N, int M, const vector<string>& grid) {
    vector<vector<int>> time(N, vector<int>(M, INT_MAX));
    queue<pair<int, int>> q;
    for (const auto& p : starts) {
        int r = p.first, c = p.second;
        time[r][c] = 0;
        q.push(p);
    }
    vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    
    while (!q.empty()) {
        auto [r, c] = q.front();
        q.pop();
        int t = time[r][c];
        
        for (const auto& dir : directions) {
            int nr = r + dir.first, nc = c + dir.second;
            if (nr >= 0 && nr < N && nc >= 0 && nc < M && grid[nr][nc] != '*' && time[nr][nc] == INT_MAX) {
                time[nr][nc] = t + 1;
                q.push({nr, nc});
            }
        }
    }
    
    return time;
}

int solve(int N, int M, const vector<string>& grid) {
    vector<pair<int, int>> fire_starts;
    pair<int, int> sanyi_start;

    for (int r = 0; r < N; ++r) {
        for (int c = 0; c < M; ++c) {
            if (grid[r][c] == 'X') {
                fire_starts.push_back({r, c});
            }
            if (grid[r][c] == 'S') {
                sanyi_start = {r, c};
            }
        }
    }
    vector<vector<int>> fire_time = bfs(fire_starts, N, M, grid);
    vector<vector<int>> sanyi_time = bfs({sanyi_start}, N, M, grid);
    int count = 0;
    for (int r = 0; r < N; ++r) {
        for (int c = 0; c < M; ++c) {
            if (grid[r][c] == '.' || grid[r][c] == 'S') {
                if (sanyi_time[r][c] < fire_time[r][c]) {
                    count++;
                }
            }
        }
    }
    
    return count;
}

int main() {
    int N, M;
    cin >> N >> M;
    
    vector<string> grid(N);
    for (int i = 0; i < N; ++i) {
        cin >> grid[i];
    }
    
    cout << solve(N, M, grid) << endl;
    return 0;
}