#include<bits/stdc++.h>
using namespace std;

const int MAX = 1000;
char lavirint[MAX][MAX];
int vremeV[MAX][MAX];
int vremeS[MAX][MAX];
int n, m;
queue<pair<int, int>> redV, redS;

void BFSV() {
    while (!redV.empty()) {
        int x = redV.front().first;
        int y = redV.front().second;
        
        redV.pop();
        
        int delta_x[] = { -1, 0, 1, 0 };
		int delta_y[] = { 0, 1, 0, -1 };

        for (int smer = 0; smer < 4; smer++) {
            int novo_x = x + delta_x[smer];
			int novo_y = y + delta_y[smer];
            
            if (novo_x >= 0 and novo_x < n and novo_y >= -1 and novo_y < m and lavirint[novo_x][novo_y] == '.' and vremeV[novo_x][novo_y] == -1) {
                vremeV[novo_x][novo_y] = vremeV[x][y] + 1;
                redV.emplace(novo_x, novo_y);
            }
        }
    }
}

void BFSS() {
    while (!redS.empty()) {
        int x = redS.front().first;
        int y = redS.front().second;
        
        redS.pop();

		int delta_x[] = { -1, 0, 1, 0 };
		int delta_y[] = { 0, 1, 0, -1 };
		
        for (int smer = 0; smer < 4; smer++) {
            int novo_x = x + delta_x[smer];
			int novo_y = y + delta_y[smer];
            
            if (novo_x >= 0 and novo_x < n and novo_y >= 0 and novo_y < m and lavirint[novo_x][novo_y] == '.' and vremeS[novo_x][novo_y] == -1) {
                vremeS[novo_x][novo_y] = vremeS[x][y] + 1;
                redS.emplace(novo_x, novo_y);
            }
        }
    }
}

int main() {
	ios_base::sync_with_stdio(false);
	
    cin >> n >> m;

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            cin >> lavirint[i][j];
            vremeV[i][j] = -1;
            vremeS[i][j] = -1;

            if (lavirint[i][j] == 'X') {
                vremeV[i][j] = 0;
                redV.emplace(i, j);
            }
            if (lavirint[i][j] == 'S') {
                vremeS[i][j] = 0;
                redS.emplace(i, j);
            }
        }
    }

   
    BFSV();
    BFSS();

    int brojac = 1;
    
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (lavirint[i][j] == '.' and vremeS[i][j] != -1 and (vremeV[i][j] == -1 or vremeS[i][j] < vremeV[i][j])) {
                brojac++;
            }
        }
    }

    cout << brojac;

    return 0;
}