#!/usr/bin/perl -w

use strict;

my @seats = map { chomp; [ split // ] } (<>);

my $cols = @{ $seats[0] };
my $rows = @seats;

print "$cols x $rows\n";

my @neighs;
for my $row (0 .. $rows-1) {
	my @neigh_row;
	for my $col (0 .. $cols-1) {
		my @neigh_seats;
		for my $add ([-1, -1], [-1, 0], [-1, 1],
			[0, -1], [0, 1],
			[1, -1], [1, 0], [1, 1]) {
			my ($row1, $col1) = ($row, $col);
			while (1) {
				$row1 += $add->[0];
				$col1 += $add->[1];
				last if $row1 >= $rows || $row1 < 0
					|| $col1 >= $cols || $col1 < 0;
				if ($seats[$row1]->[$col1] ne '.') {
					push @neigh_seats, [$row1, $col1];
					last;
				}
			}
		}
		push @neigh_row, \@neigh_seats;
	}
	push @neighs, \@neigh_row;
}

while (1) {
	my $was_change = 0;
	my $occup = 0;
	my @newseats;
	for my $row (0 .. $rows-1) {
		my @newrow;
		for my $col (0 .. $cols-1) {
			my $neigh = '';
			for my $nl (@{ $neighs[$row]->[$col] }) {
				$neigh .= $seats[$nl->[0]]->[$nl->[1]];
			}
			my $neigh_empty =()= $neigh =~ /L/g;
			my $neigh_occup =()= $neigh =~ /#/g;

			if ($seats[$row]->[$col] eq 'L' && !$neigh_occup) {
				push @newrow, '#';
				$was_change = 1;
				$occup++;
			} elsif ($seats[$row]->[$col] eq '#' && $neigh_occup >= 5) {
				push @newrow, 'L';
				$was_change = 1;
			} else {
				push @newrow, $seats[$row]->[$col];
				$occup++ if $seats[$row]->[$col] eq '#';
			}
		}
		push @newseats, \@newrow;
	}
	@seats = @newseats;
	# for my $row (@seats) {
	# 	print @$row, "\n";
	# }
	print "$occup occupied seats\n";
	# print "\n";
	last if !$was_change;
}


