using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {

        string[] dimensions = Console.ReadLine().Split();
        int N = int.Parse(dimensions[0]);
        int M = int.Parse(dimensions[1]);

        char[,] labyrinth = new char[N, M];
        Queue<(int, int)> fireQueue = new Queue<(int, int)>();
        int steveX = -1, steveY = -1;

        for (int i = 0; i < N; i++)
        {
            string row = Console.ReadLine();
            for (int j = 0; j < M; j++)
            {
                labyrinth[i, j] = row[j];
                if (row[j] == 'X')
                {
                    fireQueue.Enqueue((i, j));
                }
                else if (row[j] == 'S')
                {
                    steveX = i;
                    steveY = j;
                }
            }
        }

        int[,] fireTime = new int[N, M];
        for (int i = 0; i < N; i++)
            for (int j = 0; j < M; j++)
                fireTime[i, j] = int.MaxValue;

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

        while (fireQueue.Count > 0)
        {
            var (x, y) = fireQueue.Dequeue();
            for (int d = 0; d < 4; d++)
            {
                int nx = x + dx[d];
                int ny = y + dy[d];
                if (nx >= 0 && nx < N && ny >= 0 && ny < M && labyrinth[nx, ny] == '.' && fireTime[nx, ny] == int.MaxValue)
                {
                    fireTime[nx, ny] = fireTime[x, y] + 1;
                    fireQueue.Enqueue((nx, ny));
                }
            }
        }
        Queue<(int, int, int)> steveQueue = new Queue<(int, int, int)>();
        steveQueue.Enqueue((steveX, steveY, 0));
        bool[,] visited = new bool[N, M];
        visited[steveX, steveY] = true;

        int reachableFields = 0;

        while (steveQueue.Count > 0)
        {
            var (x, y, time) = steveQueue.Dequeue();

            if (fireTime[x, y] > time)
            {
                reachableFields++;
            }

            for (int d = 0; d < 4; d++)
            {
                int nx = x + dx[d];
                int ny = y + dy[d];
                if (nx >= 0 && nx < N && ny >= 0 && ny < M && !visited[nx, ny] && labyrinth[nx, ny] == '.' && fireTime[nx, ny] > time + 1)
                {
                    visited[nx, ny] = true;
                    steveQueue.Enqueue((nx, ny, time + 1));
                }
            }
        }
        Console.WriteLine(reachableFields);
    }
}