Search code examples
algorithmpath-finding

Finding all paths of length n between two points in a tile grid


I have a 2D tile-based map with two points which sit adjacent to each other. I would like to find all paths of length n between these two points (the points are always adjacent and the value of n would always be at least 3 so these would never be the shortest paths), with the possibility of excluding any path which passes through one or more arbitrarily defined points.

I've looked into many pathfinding algorithms, but am having trouble coming up with a way to modify them to return all paths with a precise length. Could someone point me in the right direction?


Solution

  • Simply run an exhaustive search. You can prune some branches that would never reach your destination anyway:

    search(from, to, n):
        if from is outside boundaries: return
        if distance(from, to) > n: return
        if n == 0:
            if from == to:
                do something with your path
            return
        search(left of from,  to, n-1)
        search(right of from, to, n-1)
        search(up of from,    to, n-1)
        search(down  of from, to, n-1)
    

    If your paths need to have no repeated points, just keep track as you would normally do with a DFS, but remember to unmark as visited when you exit a node (so you can visit it again in another path).