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

using namespace std;

int N, M,k;
vector<vector<char>> maze;
vector<vector<int>> fire_time, steve_time;
queue<pair<int, int>> fire_queue, steve_queue;

int dir_x[] = {-1, 1, 0, 0};
int dir_y[] = {0, 0, -1, 1};

bool is_valid(int x, int y) {
    return x >= 0 && x < N && y >= 0 && y < M && maze[x][y] != '*';
}

void fire_bfs() {
    while (!fire_queue.empty()) {
        auto p = fire_queue.front();
        fire_queue.pop();
        int x = p.first, y = p.second;
        
        for (int i = 0; i < 4; ++i) {
            int nx = x + dir_x[i], ny = y + dir_y[i];
            if (is_valid(nx, ny) && fire_time[nx][ny] == -1) {
                fire_time[nx][ny] = fire_time[x][y] + 1;
                fire_queue.push({nx, ny});
            }
        }
    }
}

void steve_bfs() {
    while (!steve_queue.empty()) {
        auto p = steve_queue.front();
        steve_queue.pop();
        int x = p.first, y = p.second;
        
        for (int i = 0; i < 4; ++i) {
            int nx = x + dir_x[i], ny = y + dir_y[i];
            if (is_valid(nx, ny) && steve_time[nx][ny] == -1) {
                if (fire_time[nx][ny] == -1 || fire_time[nx][ny] > steve_time[x][y] + 1) {
                    steve_time[nx][ny] = steve_time[x][y] + 1;
                    steve_queue.push({nx, ny});
                }
            }
        }
    }
}

int main() {
    cin >> N >> M;
    
    maze.resize(N, vector<char>(M));
    fire_time.assign(N, vector<int>(M, -1));
    steve_time.assign(N, vector<int>(M, -1));

    pair<int, int> steve_pos;
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            cin >> maze[i][j];
            if (maze[i][j] == 'X') {
                fire_queue.push({i, j});
                fire_time[i][j] = 0;
            }
            if (maze[i][j] == 'S') {
                steve_pos = {i, j};
                steve_time[i][j] = 0;
                steve_queue.push({i, j});
            }
        }
    }

    fire_bfs();
    steve_bfs();

    int valid_count = 0;
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            if (maze[i][j] == '.' && steve_time[i][j] != -1) {
                if (fire_time[i][j] == -1 || fire_time[i][j] >= steve_time[i][j]) {
                    valid_count++;
                }
            }
        }
    }
    k = valid_count + 1;
    cout << k << endl;
    return 0;
}