I would like to find all the best paths for the problem in this question
The frog's longest Smallest Jump
using non recursive depth first search (dfs). Basically each stone is a vertex of a graph and the goal vertex is reaching the opposite shore.
In pseudo code it would be something like the following (using a recursive implementation of dfs)
dfs( currentLocation, visited):
if currentLocation is opposite bank:
return (best jump 0, empty path)
for each rock R not in visited set: // treat opposite bank as a rock here
(maxHop, path) = dfs( R, visited + currentLocation )
hop = distance( currentLocation, R)
path = [R] + path
if hop > maxHop then maxHop = hop
# find best hop, path pair over all R
if longest < best_jump:
best_jump = longest
best_path = (i, j, k)
return (best hop, best path)
I am having trouble figuring out how to tweak the following non recursive python implementation of dfs
def dfs_paths(graph, start, goal):
stack = [(start, [start])]
while stack:
(vertex, path) = stack.pop()
for next in graph[vertex].difference(set(path)):
if next == goal:
yield path + [next]
else:
stack.append((next, path + [next]))
to take into account the hops lengths. The graph in this implementation is a dictionary like
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
but in the jumps problem I need to replace the characters with a representation of the stones and the far shore. I could then get the paths through
paths=list(dfs_paths(graph, start_goal, end_goal))