using System;
using System.Collections.Generic;

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

        char[,] lavirint = new char[N, M];
        Queue<(int x, int y, int vreme)> vatraQueue = new Queue<(int x, int y, int vreme)>();
        int[,] vremeVatre = new int[N, M];
        (int x, int y) stevaStart = (-1, -1);

        for (int i = 0; i < N; i++)
        {
            string linija = Console.ReadLine();
            for (int j = 0; j < M; j++)
            {
                lavirint[i, j] = linija[j];
                vremeVatre[i, j] = int.MaxValue;
                if (lavirint[i, j] == 'X')
                {
                    vatraQueue.Enqueue((i, j, 0));
                    vremeVatre[i, j] = 0;
                }
                else if (lavirint[i, j] == 'S')
                {
                    stevaStart = (i, j);
                }
            }
        }

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

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

        Queue<(int x, int y, int vreme)> stevaQueue = new Queue<(int x, int y, int vreme)>();
        bool[,] posetio = new bool[N, M];
        stevaQueue.Enqueue((stevaStart.x, stevaStart.y, 0));
        posetio[stevaStart.x, stevaStart.y] = true;

        int bezbednaPolja = 0;

        while (stevaQueue.Count > 0)
        {
            var (x, y, vreme) = stevaQueue.Dequeue();

            if (vreme < vremeVatre[x, y])
            {
                bezbednaPolja++;
                for (int d = 0; d < 4; d++)
                {
                    int nx = x + dx[d];
                    int ny = y + dy[d];
                    if (nx >= 0 && ny >= 0 && nx < N && ny < M && lavirint[nx, ny] == '.' && !posetio[nx, ny] && vreme + 1 < vremeVatre[nx, ny])
                    {
                        posetio[nx, ny] = true;
                        stevaQueue.Enqueue((nx, ny, vreme + 1));
                    }
                }
            }
        }

        Console.WriteLine(bezbednaPolja);
    }
}