eval"H,W,*A="+`dd`.split*?,
B=A.pop H*W
d=[1<<12800]+[0]*~-W
H.times{
  t=A.shift(W).zip(B.shift W).map{|a,b|(a-b).abs}
  n=0;d=d.zip(t).map{|d,t|d|=n;n=d<<t|d>>t}
}
p (0..25600).map{|i|(12800-i*d[-1][i]).abs}.min
