def g;gets.split.map(&:to_i)end def isKadomatsuSequence a a.minmax.index(a[1])&&a.uniq==a end w,h=g m=(1..h).map{g<<0}<<[0]*w q=[[0,0,[0,0,m[0][0]],0]] memo={} p (while q[0] y,x,l,s=q.shift next if memo[[y,x,l]] memo[[y,x,l]]=1 break s if [y,x]==[h-1,w-1] [[y+1,x],[y,x+1],[y-1,x],[y,x-1]].each{|dy,dx| dl=l[1,2]+[m[dy][dx]] if m[dy][dx]>0 && (dl[0]==0 || isKadomatsuSequence(dl)) q<<[dy,dx,dl,s+1] end } end)||-1