day 15, part 2 - thanks again alderwick!
This commit is contained in:
parent
a875a494b6
commit
5817e83f76
|
@ -0,0 +1,37 @@
|
|||
# algorithm proposed by alderwick :)
|
||||
BEGIN{ FS = "" }
|
||||
|
||||
function p(x,y){ return x","y }
|
||||
|
||||
function risk(x,y){
|
||||
x--; y--; # zero based
|
||||
return (r[p(x%NF+1,y%NF+1)] + int(x/NF) + int(y/NR)-1)%9 + 1
|
||||
}
|
||||
|
||||
{ for(i=1;i<=NF;i++) r[p(i,NR)] = $i }
|
||||
|
||||
END{
|
||||
s[p(1,1)] = 0
|
||||
target = 1
|
||||
while(!(p(NF*5,NR*5) in s)){
|
||||
if(target%100==0) print "target:",target
|
||||
delete ns
|
||||
for(i in s){
|
||||
split(i,arr,",")
|
||||
x = arr[1]; y=arr[2]
|
||||
cs = s[p(x,y)]
|
||||
if(cs<target-9) continue # too far from target score
|
||||
if(x>1 && risk(x-1,y)+cs==target && s[p(x-1,y)]=="" )
|
||||
ns[p(x-1,y)] = target # left
|
||||
if(x<NF*5 && risk(x+1,y)+cs==target && s[p(x+1,y)]=="" )
|
||||
ns[p(x+1,y)] = target #right
|
||||
if(y>1 && risk(x,y-1)+cs==target && s[p(x,y-1)]=="" )
|
||||
ns[p(x,y-1)] = target # up
|
||||
if(y<NR*5 && risk(x,y+1)+cs==target && s[p(x,y+1)]=="" )
|
||||
ns[p(x,y+1)] = target # down
|
||||
}
|
||||
for(i in ns) s[i] = ns[i]
|
||||
target++
|
||||
}
|
||||
print s[p(NF*5,NR*5)]
|
||||
}
|
Loading…
Reference in New Issue