#!/usr/bin/perl -w

use v5.38;
use experimental 'multidimensional';
$; = ';';

my @map;
my ($sx, $sy);

while (<>) {
	chomp;
	if (/S/g) {
		$sx = pos;
		$sy = $.;
		s/S/./;
	}
	push @map, [ split //, "#$_#" ];
}
my $xmax = $#{ $map[0] };
my $ymax = $. + 1;

push    @map, [ ('#') x ($xmax+1) ];
unshift @map, [ ('#') x ($xmax+1) ];

my %seen;

my @dx = (1, 0, -1, 0);
my @dy = (0, 1, 0, -1);

my $steps = 64;
my @q = ([ $sx, $sy, 0 ]);
while (@q) {
	my ($x, $y, $st) = @{ shift @q };
	# say "$x $y";
	next if $st >= $steps;
	for my $d (0 .. 3) {
		my $nx = $x + $dx[$d];
		my $ny = $y + $dy[$d];
		if ($map[$ny][$nx] eq '.') {
			next if $seen{$nx,$ny,$st+1}++;
			push @q, [ $nx, $ny, $st+1 ];
		}
	}
}

my $sum;
for my $y (0 .. $ymax) {
	for my $x (0 .. $xmax) {
		print $seen{$x,$y,$steps} ? 'O' : $map[$y][$x];
		$sum++ if $seen{$x,$y,$steps};
	}
	print "\n";
}
say $sum;
