fork download
  1. def calc_neighbours(node,path)
  2. length = Math.sqrt(path.length).to_i
  3. nbors = {}
  4. nbors[:right] = node+1 if node+1 >= 0 and (node+1)%length != 0 and path[node+1] != "W"
  5. nbors[:down] = node+length if node+length >= 0 and node+length < path.length and path[node+length] != "W"
  6. nbors[:up] = node-length if node-length >= 0 and path[node-length] != "W"
  7. nbors[:left] = node-1 if node-1 >= 0 and node%length != 0 and path[node-1] != "W"
  8. return nbors.values
  9. end
  10.  
  11. def calc_path(path)
  12. path = path.split('')
  13. path.each_slice(Math.sqrt(path.length)) {|x| puts x.join(" ")}
  14. end_node = path.index("E")
  15. distance = Array(0..path.length).map! {|x| x = [0,(1/0.0)]}
  16. previous = Array(0..path.length)
  17. distance[0] = [0,0]
  18.  
  19. while distance.min[0] != 1
  20. current = distance.index(distance.min)
  21. break if path[current] == "E"
  22. results = calc_neighbours(current,path)
  23. if distance[current][1] == (1/0.0)
  24. break
  25. end
  26. results.each do |x|
  27. if distance[current][1] + 1 < distance[x][1]
  28. distance[x][1] = distance[current][1] + 1
  29. previous[x] = current
  30. end
  31. end
  32. distance[current][0] = 1
  33. end
  34.  
  35. if distance[end_node][1] != (1/0.0)
  36. puts "TRUE #{distance[end_node][1]}"
  37. else
  38. puts "FALSE"
  39. end
  40. stack = []
  41. while previous[current] != 0
  42. stack << previous[current]
  43. current = previous[current]
  44. end
  45. stack.each{|x| path[x] = "+"}
  46. path.each_slice(Math.sqrt(path.length)) {|x| puts x.join(" ")}
  47. end
  48.  
  49. input = "8S...W....WW.W.W..W..W.W.......W.WWWWWWW.E...W...WW..WWW........."
  50. calc_path(input[1..-1])
Success #stdin #stdout 0.02s 7476KB
stdin
Standard input is empty
stdout
S . . . W . . .
. W W . W . W .
. W . . W . W .
. . . . . . W .
W W W W W W W .
E . . . W . . .
W W . . W W W .
. . . . . . . .
TRUE 29
S + + + W + + +
. W W + W + W +
. W . + W + W +
. . . + + + W +
W W W W W W W +
E + + + W . . +
W W . + W W W +
. . . + + + + +