using System;
using System.Collections;
using System.Collections.Generic;

namespace C
{
    internal class Program
    {
        class Polje
        {
            public int i, j;
            public Polje(int i,int j) { this.i = i;this.j = j; }
        }

        static void Main(string[] args)
        {
            string[] s = Console.ReadLine().Split();
            int n = int.Parse(s[0]), m = int.Parse(s[1]);

            Queue<Polje> steva = new Queue<Polje>();
            Queue<Polje> vatra = new Queue<Polje>();

            char[,] mapa = new char[n, m];
            int brv = 0, brs = 0;
            for (int i = 0; i < n; i++)
            {
                string s1 = Console.ReadLine();
                for (int j = 0; j < m; j++)
                {
                    mapa[i, j] = s1[j];
                    if (s1[j] == 'S') { steva.Enqueue(new Polje(i, j)); brs++; }
                    else if (s1[j] == 'X') {vatra.Enqueue(new Polje(i, j));brv++; }
                }
            }

            int munze = 0;
            while(vatra.Count > 0 || steva.Count > 0)
            {
                int temp = 0;

                for(int i=0; i<brv;i++)
                {
                    Polje p = vatra.Dequeue();
                    if (mapa[p.i, p.j] == '.') mapa[p.i, p.j] = 'X';
                    if (p.i - 1 >= 0 && mapa[p.i - 1, p.j] == '.') { vatra.Enqueue(new Polje(p.i - 1, p.j)); temp++; }
                    if (p.j - 1 >= 0 && mapa[p.i, p.j-1] == '.') {vatra.Enqueue(new Polje(p.i, p.j-1));temp++; }
                    if (p.i + 1 <n && mapa[p.i + 1, p.j] == '.') {vatra.Enqueue(new Polje(p.i + 1, p.j));temp++; }
                    if (p.j + 1 <m && mapa[p.i, p.j+1] == '.') {vatra.Enqueue(new Polje(p.i, p.j+1));temp++; }
                }
                brv = temp;

                temp = 0;
                for(int i=0;i<brs;i++)
                {
                    Polje p = steva.Dequeue();
                    if (mapa[p.i, p.j] == '.') { mapa[p.i, p.j] = 'S'; munze++; }
                    if (p.i - 1 >= 0 && mapa[p.i - 1, p.j] == '.') {steva.Enqueue(new Polje(p.i - 1, p.j));temp++; }
                    if (p.j - 1 >= 0 && mapa[p.i, p.j - 1] == '.') {steva.Enqueue(new Polje(p.i, p.j - 1));temp++; }
                    if (p.i + 1 < n && mapa[p.i + 1, p.j] == '.') {steva.Enqueue(new Polje(p.i + 1, p.j));temp++; }
                    if (p.j + 1 < m && mapa[p.i, p.j + 1] == '.') {steva.Enqueue(new Polje(p.i, p.j + 1));temp++; }
                }
                brs = temp;
            }

            Console.WriteLine(munze+1);

            Console.ReadLine();
        }
    }
}