#!/usr/bin/perl
use 5.016;
use warnings;
use utf8;
煩悩煩悩煩煩悩煩
煩煩悩空悩悩悩悩
悩空悩空悩空悩煩
空煩煩悩悩悩煩煩
悩悩悩煩悩煩煩悩
煩悩空空悩煩悩煩
煩煩煩悩煩空悩煩
EOF
my %memo = ('' => 0);
sub __f {
my ($d, $xs, $ys, $p, $c) = @_;
my $n = 0;
my $dd = [@{$d}];
foreach([1, 0], [-1, 1], [0, 1], [1, 1]){
my $x = $p % $xs + $_->[0];
my $y = $p / $xs + $_->[1];
my $q = $p + $_->[0] + $_->[1] * $xs;
(($x < $xs) and ($y < $ys) and ($d->[$q] eq $c)) or next;
$dd->[$q] = '鐘';
$n++;
}
}
sub _f {
my ($d, $xs, $ys, $p) = @_;
my $key = join '', @{$d}[$p .. $#{$d}];
if ($d->[$p] !~ /[煩悩]/){
return $memo{$key} = _f
($d, $xs, $ys, $p + 1); }
my $min = $xs * $ys;
foreach(['煩', '悩'], ['悩', '煩']){
($d->[$p] eq $_->[0]) or next;
my ($dd, $n) = __f($d, $xs, $ys, $p, $_->[1]);
if ($n){
$min = min($min, $n + _f($dd, $xs, $ys, $p + 1));
$min = min($min, 1 + _f($d, $xs, $ys, $p + 1));
}
else {
$min = min($min, _f($d, $xs, $ys, $p + 1));
}
}
}
say f(@data);
IyEvdXNyL2Jpbi9wZXJsCnVzZSA1LjAxNjsKdXNlIHdhcm5pbmdzOwp1c2UgdXRmODsKdXNlIExpc3Q6OlV0aWwgcXcobWluKTsKCmNob21wKG15IEBkYXRhID0gc3BsaXQgL14vLCA8PCdFT0YnKTsK54Wp5oKp54Wp5oKp54Wp54Wp5oKp54WpCueFqeeFqeaCqeepuuaCqeaCqeaCqeaCqQrmgqnnqbrmgqnnqbrmgqnnqbrmgqnnhakK56m654Wp54Wp5oKp5oKp5oKp54Wp54WpCuaCqeaCqeaCqeeFqeaCqeeFqeeFqeaCqQrnhanmgqnnqbrnqbrmgqnnhanmgqnnhakK54Wp54Wp54Wp5oKp54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