Rewrite ways_from_nodes to be faster