I a got a list of tuples, each tuple representing a station on a mountain. Each station has a certain distance to another station and we can only visit stations which are below us (so we basically cannot travel the mountain upwards). The tuples look like this:
t_1 = (1, 2, 5)
t_2 = (1, 3, 4)
t_3 = (2, 3 , 10)
t_4 = (2, 4, 1)
The first element of each tuple is the station and the second element indicates there exists path to that station with a distance of 5. So we can get from station 1 to 2 with a distance of 5 or we can get from station 1 to station 3 with a distance of 4. Ultimately, we are looking for the longest distance possible, which would be 15 (We visit station 2 first, then station 3). My idea was to use DFS for this with the following code:
def dfs(graph, node, dist, res):
cur, nxt, d = node
dist += d
if len(graph[nxt]) == 0:
res[0] = max(res[0], dist)
else:
for neighbor in graph[nxt]:
dfs(graph, neighbor, dist, res)
res = [0]
for start_nodes in graph[1]:
dfs(graph, start_nodes, 0, res)
The idea is, that I check if the current node "cur" has a neighbor "nxt" and visit this neighbor in an adj. list looking like this:
graph = [[(1,2,5),(1,3,4)],[(2,3,10),(2,4,1)],[]]
if there is no neighbor, we check if we have a new max distance. I am certainly missing something, so I would appreciate if anyone finds any errors and/or flaws!