while pocetak <= kraj do
begin
x := redVatre[pocetak].x;
y := redVatre[pocetak].y;
Inc(pocetak);
for k := 1 to 4 do
begin
nx := x + dx[k];
ny := y + dy[k];
if (nx >= 1) and (nx <= N) and (ny >= 1) and (ny <= M) then
begin
if (labirint[nx, ny] = '.') and (vremeVatre[nx, ny] = -1) then
begin
vremeVatre[nx, ny] := vremeVatre[x, y] + 1;
DodajURed(redVatre, kraj, nx, ny);
end;
end;
end;
end;
end;
procedure BFSSteva();
var
x, y, nx, ny, k: Integer;
begin
while pocetak <= kraj do
begin
x := redSteve[pocetak].x;
y := redSteve[pocetak].y;
Inc(pocetak);
for k := 1 to 4 do
begin
nx := x + dx[k];
ny := y + dy[k];
if (nx >= 1) and (nx <= N) and (ny >= 1) and (ny <= M) then
begin
if (labirint[nx, ny] = '.') and (vremeSteve[nx, ny] = -1) then
begin
if (vremeVatre[nx, ny] = -1) or (vremeSteve[x, y] + 1 < vremeVatre[nx, ny]) then
begin
vremeSteve[nx, ny] := vremeSteve[x, y] + 1;
DodajURed(redSteve, kraj, nx, ny);
end;
end;
end;
end;
end;
end;
begin
readln(N, M);
for i := 1 to N do
begin
for j := 1 to M do
begin
read(labirint[i, j]);
vremeVatre[i, j] := -1;
vremeSteve[i, j] := -1;
end;
readln;
end;
pocetak := 1;
kraj := 0;
dx[1] := -1; dx[2] := 1; dx[3] := 0; dx[4] := 0;
dy[1] := 0; dy[2] := 0; dy[3] := -1; dy[4] := 1;
for i := 1 to N do
begin
for j := 1 to M do
begin
if labirint[i, j] = 'X' then
begin
DodajURed(redVatre, kraj, i, j);
vremeVatre[i, j] := 0;
end
else if labirint[i, j] = 'S' then
begin
stevaX := i;
stevaY := j;
end;
end;
end;
BFSVatra();
pocetak := 1;
kraj := 0;
DodajURed(redSteve, kraj, stevaX, stevaY);
vremeSteve[stevaX, stevaY] := 0; 
BFSSteva();
brojPolja := 0;
for i := 1 to N do
begin
for j := 1 to M do
begin
if (vremeSteve[i, j] <> -1) and ((vremeVatre[i, j] = -1) or (vremeSteve[i, j] < vremeVatre[i, j])) then
Inc(brojPolja);
end;
end;
writeln(brojPolja);
end.