Sure! Here's a recursive depth-first search algorithm in Python that finds the maximum score achievable by traversing a directed acyclic graph (DAG) from a given start node to an end node while following the specified constraints:
def dfs(graph, start, end, visited=[]):
if start == end:
return 0
visited.append(start)
max_score = float('-inf')
for neighbor in graph[start]:
if neighbor not in visited:
score = dfs(graph, neighbor, end, visited)
if score != float('-inf'):
edge_score = graph[start][neighbor]
max_score = max(max_score, score + edge_score)
visited.remove(start)
return max_score
# Example usage:
graph = {
'word1': {'word2': 5, 'word3': 10},
'word2': {'word4': 15},
'word3': {'word2': 20},
'word4': {}
}
start = 'word1'
end = 'word4'
max_score = dfs(graph, start, end)
print("Maximum score:", max_score)
In this example, graph is a dictionary representing the DAG, where each key is a word and the corresponding value is another dictionary that maps neighboring words to their edge scores.
The dfs function takes the graph, start node, end node, and an optional visited list as input. It keeps track of visited nodes to avoid revisiting them.
Inside the dfs function, we check if the current start node is the same as the end node. If so, we have reached the destination and return a score of 0.
We mark the start node as visited and initialize the max_score variable with negative infinity.
Then, we iterate over the neighbors of the start node. If a neighbor has not been visited yet, we recursively call the dfs function to explore that neighbor. We update the max_score if a higher score is found.
Finally, we remove the start node from the visited list and return the max_score.
Note: The implementation assumes that the start and end nodes are present in the graph and that there is at least one path from the start to the end node.