Assume that a function takes s
(origin hexagon), f
(target hexagon) and n
(length of the path) values as parameters and outputs list of all possible paths that has n length. To visualize the problem please check the figure below:
Let's say our origin (s
) is the red dotted hex (2, 3)
and the target (f
) is the blue dotted one (5, 2)
. We want to reach blue dotted hex in 5 steps (n = 5
). Also consider that if a walk reaches a specific hex, it may stay in that hex as well in the next step. In other words, one of the possible paths can be (3, 2) - (4, 2) - (5, 2) - (5, 2) - (5, 2)
. It is also counted as 5-length path.
These are some example paths from (2, 3)
to (5, 2)
:
(1, 3) - (2, 3) - (3, 2) - (4, 3) - (5, 2)
(3, 3) - (4, 4) - (5, 4) - (5, 3) - (5, 2)
(2, 3) - (2, 3) - (3, 3) - (4, 3) - (5, 2)
I want to find all of these paths in a way. However, I could not determine which algorithm gives the most efficient solution to handle this problem. The first thing comes to mind is to use depth-first-search but I wonder is there any better alternative to use in this case.
Say you define the following recursive function, returning a list of lists of pairs, where each list of pairs is a path from
from
toto
with lengthi
:Then you just need to call it with your source, target, and required length.
For a hex grid like this,
the Manhattan distance between two nodes can be computed by using:
This problem had been discussed in these questions before:
I believe that we can enhance Ami's answer by combining it with
manhattan_dist
:Lastly, as you can see, there is a helper function to get indices of neighbor nodes:
The main idea is simply pruning a node if its Manhattan distance to the target node is larger than the length
n
of the current recursive call. To exemplify, if we can go from(1, 1)
to(0, 3)
in two steps (n = 2
), all neighbor nodes except(1, 2)
should be pruned.