#!/usr/bin/perl -w

use v5.38;
use experimental 'multidimensional', 'for_list', 'builtin';
use builtin 'indexed';
use List::Util;
use Y::AoC::Task;
$; = ';';
# t;

my @map = map { chomp; [ split // ] } <>;
my $xmax = @{ $map[0] };
my $ymax = @map;

my $sum;

my %seen;

for my $y (0 .. $ymax-1) {
for my $x (0 .. $xmax-1) {
	my $n = $map[$y][$x];
	next if $n !~ /\d/ || $seen{$x,$y}++;
	my $dx = 1;
	my $is_neigh = 0;
	if ($x > 0) {
		if ($y > 0 && $map[$y-1][$x-1] !~ /\./) { $is_neigh = 1; }
		if ($map[$y][$x-1] !~ /\./) { $is_neigh = 1; }
		if ($y < $ymax-1 && $map[$y+1][$x-1] !~ /\./) { $is_neigh = 1; }
	}
	say "First $is_neigh";
	if ($y > 0 && $map[$y-1][$x] !~ /\./) { $is_neigh = 1; }
	if ($y < $ymax-1 && $map[$y+1][$x] !~ /\./) { $is_neigh = 1; }
	while ($x+$dx < $xmax && $map[$y][$x+$dx] =~ /\d/) {
		$n*=10; $n+= $map[$y][$x+$dx];
		say "First $is_neigh at ", $x+$dx;
		if ($y > 0 && $map[$y-1][$x+$dx] !~ /\./) { say $y-1, " ", $x+$dx; $is_neigh = 1; }
		if ($y < $ymax-1 && $map[$y+1][$x+$dx] !~ /\./) { $is_neigh = 1; }
		$seen{$x+$dx,$y} = 1;
		$dx++;
	}
	say "Before last $is_neigh at ", $x+$dx;
	if ($x + $dx < $xmax) {
		if ($y > 0 && $map[$y-1][$x+$dx] !~ /\./) { say $y-1, " ", $x+$dx; $is_neigh = 1; }
		if ($y < $ymax-1 && $map[$y+1][$x+$dx] !~ /\./) { $is_neigh = 1; }
		if ($x+$dx < $xmax-1 && $map[$y][$x+$dx] !~ /\./) { $is_neigh = 1; }
	}
	$sum += $n if $is_neigh;
	if ($is_neigh) { say "$n at $x,$y" }
} }

say $sum;
