using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        string[] dimensions = Console.ReadLine().Split();
        int n = int.Parse(dimensions[0]);
        int m = int.Parse(dimensions[1]);

        char[,] maze = new char[n, m];
        int stevaX = -1, stevaY = -1;
        Queue<(int, int)> fireQueue = new Queue<(int, int)>();

        for (int i = 0; i < n; i++)
        {
            string line = Console.ReadLine();
            for (int j = 0; j < m; j++)
            {
                maze[i, j] = line[j];
                if (maze[i, j] == 'S')
                {
                    stevaX = i;
                    stevaY = j;
                }
                else if (maze[i, j] == 'X')
                {
                    fireQueue.Enqueue((i, j));
                }
            }
        }

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

        int[,] fireTime = new int[n, m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                fireTime[i, j] = -1;

        while (fireQueue.Count > 0)
        {
            var (x, y) = fireQueue.Dequeue();
            if (fireTime[x, y] != -1) continue;

            fireTime[x, y] = 0;

            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 && maze[nx, ny] != '*' && fireTime[nx, ny] == -1)
                {
                    fireTime[nx, ny] = fireTime[x, y] + 1;
                    fireQueue.Enqueue((nx, ny));
                }
            }
        }

        Queue<(int, int)> stevaQueue = new Queue<(int, int)>();
        stevaQueue.Enqueue((stevaX, stevaY));
        int[,] stevaTime = new int[n, m];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                stevaTime[i, j] = -1;

        stevaTime[stevaX, stevaY] = 0;

        while (stevaQueue.Count > 0)
        {
            var (x, y) = stevaQueue.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 && maze[nx, ny] != '*' && stevaTime[nx, ny] == -1)
                {
                    stevaTime[nx, ny] = stevaTime[x, y] + 1;
                    stevaQueue.Enqueue((nx, ny));
                }
            }
        }

        int escapeCount = 0;
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                if (maze[i, j] == '.' && stevaTime[i, j] != -1 && (fireTime[i, j] == -1 || stevaTime[i, j] < fireTime[i, j]))
                {
                    escapeCount++;
                }
            }
        }

        Console.WriteLine(escapeCount);
    }
}