fork(1) download
  1. base=[1,2,3,4,5,6,7,8,9]
  2. lens=[[]]
  3. 9.times{|i|
  4. lens<<[0]
  5. 9.times{|j|
  6. x1=i%3
  7. y1=i/3
  8. x2=j%3
  9. y2=j/3
  10. lens[i+1]<<(x1-x2).abs+(y1-y2).abs
  11. }
  12. }
  13. d=gets.chomp.split("").map{|e| e.to_i}
  14. ans=10**18
  15.  
  16. base.permutation{|e|
  17. t=1
  18. d.each_cons(2){|n,n2|
  19. t+=lens[e[n-1]][e[n2-1]]+1
  20. break if ans<t
  21. }
  22. ans=t if t<ans
  23. }
  24. puts ans
Success #stdin #stdout 0.76s 8028KB
stdin
123456789
stdout
51
17