#!/usr/bin/perl -w

use v5.36;
use strict;
use experimental 'multidimensional';

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

my $rows = @map;
my $cols = @{ $map[0] };
my $periods = 1000000000;

my $gen = 0;
my %seen;
while ($gen++ < $periods) {
	my %total;
	my @nmap;
	say "gen $gen";
	for my $y (0 .. $rows-1) {
		my @row;
		for my $x (0 .. $cols-1) {
			my %count = map { $_ => 0 } ('#', '|', '.');
			for my $neigh ([-1,-1], [0, -1], [1, -1],
				[-1, 0], [1, 0],
				[-1, 1], [0, 1], [1, 1]) {
				my $nx = $x + $neigh->[0];
				my $ny = $y + $neigh->[1];
				next if $nx < 0 || $nx >= $cols
					|| $ny < 0 || $ny >= $cols;
				$count{$map[$ny][$nx]}++;
			}
			my $self = $map[$y][$x];
			if ($self eq '.' && $count{'|'} >= 3) {
				$self = '|';
			} elsif ($self eq '|' && $count{'#'} >= 3) {
				$self = '#';
			} elsif ($self eq '#' &&
				($count{'#'} == 0 || $count{'|'} == 0)) {
				$self = '.';
			}
			push @row, $self;
			$total{$self}++;
		}
		push @nmap, \@row;
	}
	@map = @nmap;
	my $state = join('', map { join('', @$_, "\n") } @map);
	
	say $total{"#"} * $total{'|'};
	if (defined $seen{$state} && $gen < 500) {
		say "at $gen: the same state seen at $seen{$state}";
		my $period = $gen - $seen{$state};
		say "period $period";
		$gen += $period * int(($periods-1-$gen)/$period);
		say " => $gen";
	}
	$seen{$state} = $gen;
}

