#!/usr/bin/perl -w

use v5.16;

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

my $sum;
for (1 .. 100) {
	my %f;
	my @q;
	for my $x (0 .. 9) {
	for my $y (0 .. 9) {
		next if $f{$x,$y};
		next if ++$m[$y][$x] < 10;
		$f{$x,$y} = 1;
		push @q, [$x,$y];
		say "flashed:$x,$y";
	} }
	while (@q) {
		my $p = shift @q;
		my ($x2, $y2) = @$p;

		for my $dx (-1 .. 1) {
		for my $dy (-1 .. 1) {
			next if $dx == 0 && $dy == 0;
			next if $x2+$dx < 0 || $x2+$dx > 9;
			next if $y2+$dy < 0 || $y2+$dy > 9;
			next if $f{$x2+$dx,$y2+$dy};
			say $x2+$dx, ',', $y2+$dy, ' >',$m[$y2+$dy][$x2+$dx];
			next if ++$m[$y2+$dy][$x2+$dx] < 10;
			$f{$x2+$dx,$y2+$dy} = 1;
			push @q, [$x2+$dx, $y2+$dy];
			say "flashed ", $x2+$dx,',',$y2+$dy;
		} }
	}
	for my $p (keys %f) {
		my ($x, $y) = split /$;/, $p;
		$m[$y][$x] = 0;
	}
	say "Step $_ flashes ", scalar keys %f;
	say join("\n", map { join('', @$_) } @m);
	say;
	# last if $_ > 1;
	$sum += keys %f;
}

say $sum;

