Last active
June 7, 2021 19:43
-
-
Save DrI-T/f85e629397b23cc6d779bef4c58e2fc0 to your computer and use it in GitHub Desktop.
count numbers of path from 0,0 to n,m avoiding obstacles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
# number of paths from [0,0] to [n,m] ... | |
my $seed = srand(2323043460); | |
printf "seed: %s\n",$seed; | |
my ($n,$m) = (6,5); | |
my @A = (); | |
for (0 ..$m-1) { | |
push @A, [ map { rand(1)>0.5?1:0; } (0 .. $n-1) ] | |
} | |
$A[0][0] = 1; | |
$A[$m-1][$n-1] = 1; | |
my $result = &hack(\@A); | |
sub hack { | |
our @ar = @{$_[0]}; | |
our $m = scalar(@ar); | |
our $n = scalar(@{$ar[0]}); | |
print "n: $n\n"; | |
print "m: $m\n"; | |
for my $j (0 .. $#ar) { | |
printf "ar[%2d]: [%s]\n",$j,join(',',@{$ar[$j]}); | |
} | |
my $res = &nbp(0,0); | |
sub nbp { | |
my ($x,$y) = @_; | |
if ($x == $n-1 && $y == $m-1 ) { print ".\n"; return 1; } | |
my ($dp,$rp) = (0,0); | |
if ($ar[$y+1][$x]) { printf " v %d,%d",$x,$y+1; $dp = &nbp($x,$y+1); } | |
if ($ar[$y][$x+1]) { printf " -> %s,%d",$x+1,$y; $rp = &nbp($x+1,$y); } | |
my $count = $dp + $rp; | |
return $count; | |
} | |
return $res; | |
} | |
print "$result\n"; | |
exit $?; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment