You can modify dfs to solve this problem. Simply add another parameter - the depth at which you currently are, then cut the dfs if the path length limit was reached before target node target. To demonstrate the idea I will use recursive implementation and I will use a global array used - the nodes visited this far on the way. Also I will assume that we've stored the graph using neighborhood list representation(let's call that neList, the neighbors of node v are at neList[v]):
used[n] = {false}
neList; // neighborhoodList
limit = 10 // max path len
void dfs(int v, int depth) {
if (depth == limit) {
if (v == target) {
print_path
} else {
return
}
}
for u in neList[v] {
if (used[u]) {
continue;
}
used[u] = true
dfs(u, depth + 1)
used[u] = false
}
}
You can optimize this approach a bit - first do a bfs from the target node to compute min_distance between target and all nodes. In the dfs only go to a neighbor u if depth + min_dist[u] <= limit.