Neo4j を使った答え
Neo4j::Session.open(:server_db, 'http://localhost:7474')
conn = Neo4j::Session.current
conn.query('MATCH (n) DETACH DELETE n')
nodes = {}
(?0..?9).each {|n| nodes[n] = Neo4j::Node.create({name: n}, :Pos) }
(?A..?Z).each {|n| nodes[n] = Neo4j::Node.create({name: n}, :Pos) }
[
[?0, ?1], [?2, ?3], [?3, ?4], [?4, ?5],
[?7, ?8], [?8, ?9], [?9, ?A],
[?C, ?D], [?F, ?G],
[?J, ?K], [?K, ?L], [?L, ?M],
[?P, ?Q], [?Q, ?R], [?S, ?T],
[?U, ?V], [?V, ?W], [?Y, ?Z],
[?0, ?6], [?6, ?C], [?C, ?I], [?I, ?O],
[?1, ?7], [?J, ?P], [?P, ?V],
[?E, ?K],
[?3, ?9], [?9, ?F], [?R, ?X],
[?G, ?M], [?M, ?S], [?S, ?Y],
[?5, ?B], [?H, ?N], [?N, ?T]
].each do |l1, l2|
n1 = nodes[l1]
n2 = nodes[l2]
Neo4j::Relationship.create(:line, n1, n2)
end
s, g = input.chars
conn.query("MATCH (s:Pos{ name: '#{s}' }), (g:Pos{ name: '#{g}' }), p = shortestPath((s)-[:line*]-(g)) RETURN length(p) AS len").to_a.first.len.to_s