One way to solve this is, instead of doing all the ways, as soon as you take one food item, make the snake move to the side that has the next food product, and then when it is on that side, use the basic 2D mesh algorithm A * for food. In other words:
Whenever a snake grabs a food product or moves to a new side of the cube, do the following:
- If the battery is on the current side of the cube, find the path to it using the A * algorithm with a 2D Manhattan heuristic distance
- If the food is on the adjacent side of the cube, find the path to the edge of the cube bordering the current side and the target side using the same path search algorithm.
- If the food product is on the opposite side of the cube, find the path from the current side with the same path search algorithm.
This does not guarantee the shortest common path, but usually it should be close to the shortest, and it should be faster because it splits the path into several phases and uses a more efficient algorithm for each phase.
source share