Problem Description
ideas and code
Ontology refers to the official problem solution, and solves it through depth-first search:
LeetCode 2065 official problem solution
Note two things:
- When repeatedly reaching a certain node, the value cannot be obtained repeatedly;
- If the starting point is an isolated point, return directly.
code show as below:
class Solution:
def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int:
# node to (node, time) list dictionary
dict_node_edge = {
}
for i, j, t in edges:
if i not in dict_node_edge.keys():
dict_node_edge[i] = [(j, t)]
else:
dict_node_edge[i].append((j, t))
if j not in dict_node_edge.keys():
dict_node_edge[j] = [(i, t)]
else:
dict_node_edge[j].append((i, t))
set_node_visit = {
0}
ans = 0
def dfs(node: int, time: int, value: int) -> None:
nonlocal ans
if node == 0:
ans = max(ans, value)
if node not in dict_node_edge.keys():
return
for node_next, time_cost in dict_node_edge[node]:
if time + time_cost <= maxTime:
if node_next not in set_node_visit:
set_node_visit.add(node_next)
dfs(node=node_next, time=time + time_cost, value=value + values[node_next])
set_node_visit.remove(node_next)
else:
dfs(node=node_next, time=time + time_cost, value=value)
dfs(node=0, time=0, value=values[0])
return ans
Among them, if the dict_node_edge dictionary uses the defaultdict type, its characteristics can be used, and there is no need to perform special treatment for the case where the starting point is an isolated point, as shown in the official solution:
class Solution:
def maximalPathQuality(self, values: List[int], edges: List[List[int]], maxTime: int) -> int:
g = defaultdict(list)
for x, y, z in edges:
g[x].append((y, z))
g[y].append((x, z))
visited = {
0}
ans = 0
def dfs(u: int, time: int, value: int) -> None:
if u == 0:
nonlocal ans
ans = max(ans, value)
for v, dist in g[u]:
if time + dist <= maxTime:
if v not in visited:
visited.add(v)
dfs(v, time + dist, value + values[v])
visited.discard(v)
else:
dfs(v, time + dist, value)
dfs(0, 0, values[0])
return ans
But according to the author's usual code habits, I usually avoid the unexpected key side effect of defaultdict, so I don't use this type.
The author's code works as follows:
Extended thinking
The idea of this question can also be used to solve the path problem of the grid map, that is, the cost or benefit of reaching each grid point is different. At this time, it cannot be solved by the original A* algorithm, and only the method of this question can be used to search. But the problem is that the search space is too large in nature, and it is difficult to complete the optimal pathfinding in a large area.