using System;
using System.Collections.Generic;

public class Program
{
    static readonly int[] dx = { -1, 1, 0, 0 };
    static readonly int[] dy = { 0, 0, -1, 1 };
    
    public static void Main()
    {
        var dimensions = Console.ReadLine().Split();
        int N = int.Parse(dimensions[0]);
        int M = int.Parse(dimensions[1]);
        
        char[,] maze = new char[N, M];
        Queue<Tuple<int, int>> fireQueue = new Queue<Tuple<int, int>>();
        Queue<Tuple<int, int>> steveQueue = new Queue<Tuple<int, int>>();
        int[,] fireTime = new int[N, M];
        int[,] steveTime = new int[N, M];
        
        Tuple<int, int> stevePos = null;
        
        for (int i = 0; i < N; i++)
        {
            var line = Console.ReadLine();
            for (int j = 0; j < M; j++)
            {
                maze[i, j] = line[j];
                fireTime[i, j] = -1;
                steveTime[i, j] = -1;
                if (line[j] == 'X')
                {
                    fireQueue.Enqueue(new Tuple<int, int>(i, j));
                    fireTime[i, j] = 0;
                }
                else if (line[j] == 'S')
                {
                    stevePos = new Tuple<int, int>(i, j);
                    steveTime[i, j] = 0;
                }
            }
        }
        
        while (fireQueue.Count > 0)
        {
            var (x, y) = fireQueue.Dequeue();
            for (int dir = 0; dir < 4; dir++)
            {
                int nx = x + dx[dir], ny = y + dy[dir];
                if (nx >= 0 && nx < N && ny >= 0 && ny < M && maze[nx, ny] == '.' && fireTime[nx, ny] == -1)
                {
                    fireTime[nx, ny] = fireTime[x, y] + 1;
                    fireQueue.Enqueue(new Tuple<int, int>(nx, ny));
                }
            }
        }

        while (steveQueue.Count > 0)
        {
            var (x, y) = steveQueue.Dequeue();
            for (int dir = 0; dir < 4; dir++)
            {
                int nx = x + dx[dir], ny = y + dy[dir];
                if (nx >= 0 && nx < N && ny >= 0 && ny < M && maze[nx, ny] == '.' && steveTime[nx, ny] == -1)
                {
                    if (fireTime[nx, ny] == -1 || fireTime[nx, ny] > steveTime[x, y] + 1)
                    {
                        steveTime[nx, ny] = steveTime[x, y] + 1;
                        steveQueue.Enqueue(new Tuple<int, int>(nx, ny));
                    }
                }
            }
        }
        
        int count = 0;
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < M; j++)
            {
                if (steveTime[i, j] != -1 && (fireTime[i, j] == -1 || steveTime[i, j] < fireTime[i, j]))
                {
                    count++;
                }
            }
        }

        Console.WriteLine(count);
    }
}