#!/usr/bin/perl -w

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

my @map;

sub sgn($x) { $x > 0 ? 1 : $x < 0 ? -1 : 0 };

my $maxy;
while (<>) {
	my ($x0, $y0);
	my @list = /(\d+)/g;

	for my ($x, $y) (@list) {
		if (!defined $x0) {
			$x0 = $x; $y0 = $y;
			$map[$y][$x] = 1;
		} else {
			while ($x0 != $x || $y0 != $y) {
				$x0 += sgn($x-$x0);
				$y0 += sgn($y-$y0);
				$map[$y0][$x0] = 1;
				$maxy = $y if !defined $maxy || $y > $maxy;
			}
		}
	}
}

my $units = 0;
while (1) {
	my ($sx, $sy) = (500, 0);

	while ($sy <= $maxy) {
		say "at $sx $sy";
		if (!$map[$sy+1][$sx]) {
			$sy++;
		} elsif (!$map[$sy+1][$sx-1]) {
			$sx--;
			$sy++;
		} elsif (!$map[$sy+1][$sx+1]) {
			$sx++;
			$sy++;
		} else {
			$map[$sy][$sx] = 2;
			last;
		}
	}
	say "stopped at $sx, $sy";
	last if $sy > $maxy;
	$units++;
}

say $units;
