in reply to Brute force vs algorithm (PWC # 100)
Classic caching problem. Each cell is computed only once.
#!/usr/bin/perl use strict; use warnings; use List::Util qw( min ); local $_ = <<END; 1 2 4 6 4 9 5 1 7 2 END my @d = map [ split ], split /\n/; my %cache; print path(0, 0), "\n"; sub path { my ($r, $c) = @_; $cache{"@_"} //= $r < $#d ? $d[$r][$c] + min(path($r+1, $c), path($r+1, $c+1)) : $d[$r][$c] }
It wasn't clear from the problem whether just the sum was needed or the whole path. This just returns 8
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Brute force vs algorithm (PWC # 100)
by LanX (Saint) on Feb 15, 2021 at 21:33 UTC | |
by tybalt89 (Monsignor) on Feb 16, 2021 at 00:14 UTC | |
by LanX (Saint) on Feb 16, 2021 at 03:42 UTC | |
by tybalt89 (Monsignor) on Feb 16, 2021 at 04:39 UTC | |
by tybalt89 (Monsignor) on Feb 16, 2021 at 05:04 UTC |