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, int)> redVatre = new Queue<(int, int)>();
        Queue<(int, int)> redSteve = new Queue<(int, int)>();
        int[,] vremeVatre = new int[N, M];
        int[,] vremeSteve = new int[N, M];

        (int pocetakSteveX, int pocetakSteveY) = (-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] = -1;
                vremeSteve[i, j] = -1;
                if (lavirint[i, j] == 'X')
                {
                    redVatre.Enqueue((i, j));
                    vremeVatre[i, j] = 0;
                }
                if (lavirint[i, j] == 'S')
                {
                    pocetakSteveX = i;
                    pocetakSteveY = j;
                    redSteve.Enqueue((i, j));
                    vremeSteve[i, j] = 0;
                }
            }
        }

        int[] pomerajX = { -1, 1, 0, 0 };
        int[] pomerajY = { 0, 0, -1, 1 };

        while (redVatre.Count > 0)
        {
            var (x, y) = redVatre.Dequeue();
            for (int i = 0; i < 4; i++)
            {
                int nx = x + pomerajX[i], ny = y + pomerajY[i];
                if (nx >= 0 && nx < N && ny >= 0 && ny < M && lavirint[nx, ny] == '.' && vremeVatre[nx, ny] == -1)
                {
                    vremeVatre[nx, ny] = vremeVatre[x, y] + 1;
                    redVatre.Enqueue((nx, ny));
                }
            }
        }

        while (redSteve.Count > 0)
        {
            var (x, y) = redSteve.Dequeue();
            for (int i = 0; i < 4; i++)
            {
                int nx = x + pomerajX[i], ny = y + pomerajY[i];
                if (nx >= 0 && nx < N && ny >= 0 && ny < M && lavirint[nx, ny] == '.' && vremeSteve[nx, ny] == -1)
                {
                    if (vremeVatre[nx, ny] == -1 || vremeSteve[x, y] + 1 < vremeVatre[nx, ny])
                    {
                        vremeSteve[nx, ny] = vremeSteve[x, y] + 1;
                        redSteve.Enqueue((nx, ny));
                    }
                }
            }
        }

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

        Console.WriteLine(rezultat);
    }
}