using System;
using System.Collections.Generic;

class Program
{
    static int[] dx = { -1, 1, 0, 0 };
    static int[] dy = { 0, 0, -1, 1 };

    static void Main()
    {
      
        var dims = Console.ReadLine().Split();
        int N = int.Parse(dims[0]);
        int M = int.Parse(dims[1]);

        char[,] labirint = new char[N, M];
        int[,] vatraT = new int[N, M];
        int[,] stevaT = new int[N, M]; 

        Queue<(int, int)> vatraQueue = new Queue<(int, int)>();
        Queue<(int, int)> stevaQueue = new Queue<(int, int)>();

        (int, int) stevaStart = (-1, -1);
        for (int i = 0; i < N; i++)
        {
            string line = Console.ReadLine();
            for (int j = 0; j < M; j++)
            {
                labirint[i, j] = line[j];
                if (labirint[i, j] == 'X')
                {
                    vatraQueue.Enqueue((i, j));
                    vatraT[i, j] = 0; 
                }
                else
                {
                    vatraT[i, j] = -1;
                }

                if (labirint[i, j] == 'S')
                {
                    stevaStart = (i, j);
                    stevaT[i, j] = 0; 
                }
                else
                {
                    stevaT[i, j] = -1; 
                }
            }
        }

        while (vatraQueue.Count > 0)
        {
            var (x, y) = vatraQueue.Dequeue();
            for (int i = 0; i < 4; i++)
            {
                int nx = x + dx[i], ny = y + dy[i];
                if (nx >= 0 && ny >= 0 && nx < N && ny < M && labirint[nx, ny] == '.' && vatraT[nx, ny] == -1)
                {
                    vatraT[nx, ny] = vatraT[x, y] + 1;
                    vatraQueue.Enqueue((nx, ny));
                }
            }
        }

        stevaQueue.Enqueue(stevaStart);
        stevaT[stevaStart.Item1, stevaStart.Item2] = 0;

        while (stevaQueue.Count > 0)
        {
            var (x, y) = stevaQueue.Dequeue();
            for (int i = 0; i < 4; i++)
            {
                int nx = x + dx[i], ny = y + dy[i];
                if (nx >= 0 && ny >= 0 && nx < N && ny < M && labirint[nx, ny] == '.' && stevaT[nx, ny] == -1)
                {

                    if (vatraT[nx, ny] == -1 || stevaT[x, y] + 1 < vatraT[nx, ny])
                    {
                        stevaT[nx, ny] = stevaT[x, y] + 1;
                        stevaQueue.Enqueue((nx, ny));
                    }
                }
            }
        }

        int rezultat = 0;
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < M; j++)
            {
                if (labirint[i, j] == '.' && stevaT[i, j] != -1 && (vatraT[i, j] == -1 || stevaT[i, j] < vatraT[i, j]))
                {
                    rezultat++;
                }
            }
        }

        Console.WriteLine(rezultat);
    }
}