#!/usr/bin/perl -w

use v5.16;
use Data::Dumper;

$; = ',';
my @m;
my ($maxx, $maxy) = (0, 0);
while (<>) {
	chomp;
	push @m, [ split // ];
	$maxx = length;
	$maxy++;
}

my %cost = ("0,0" => 0);
my @todo = ([0, 0]);

while (my $p = shift @todo) {
	my ($sx, $sy) = @$p;
	for my $d ([ 0, 1], [0, -1], [1, 0], [-1, 0]) {
		my $dx = $sx + $d->[0];
		my $dy = $sy + $d->[1];
		next if $dx < 0 || $dx >= $maxx || $dy < 0 || $dy >= $maxy;
		if (!defined $cost{$dx,$dy}
			|| $cost{$dx,$dy} > $cost{$sx,$sy} + $m[$dy][$dx]) {
			$cost{$dx,$dy} = $cost{$sx,$sy} + $m[$dy][$dx];
			push @todo, [$dx,$dy];
		}
	}
}

say $cost{$maxx-1,$maxy-1};

