Problem Description
Given an undirected graph with n nodes (0-indexed) where each node i has an associated value values[i] and each edge is represented by [u, v, time] (indicating that it takes "time" seconds to travel between u and v), find a valid path which starts and ends at node 0, takes at most maxTime seconds, and collects the maximum possible sum of unique node values (each node’s value is counted only once regardless of how many times it is visited).
Key Insights
- The problem is solved by exploring all possible paths starting and ending at node 0 with a DFS/backtracking approach.
- When revisiting a node, only the first visit contributes its value; subsequent visits do not affect quality.
- Precompute the shortest time from every node back to node 0 using Dijkstra’s algorithm to prune DFS paths that cannot possibly return in time.
- The graph has a limited number of edges per node (at most 4), keeping the DFS branching factor low even though n can be relatively high.
Space and Time Complexity
Time Complexity: O(2^(n)) in the worst case due to full exploration, but practical constraints (maxTime and degree limits) keep it manageable. Space Complexity: O(n + E) for storing the graph and recursion stack, where E is the number of edges.
Solution
We use a DFS/backtracking strategy to traverse the graph, starting at node 0. Each DFS call tracks the current node, elapsed time, current quality (sum of unique node values visited), and a count array to decide if a node’s value should be added. Before exploring further, we check if the remaining time is at least the minimum time required to return from the current node to 0 (precomputed using Dijkstra). When we return to node 0, we update the result with the highest quality obtained. We construct an adjacency list from the input edges and use recursion with careful backtracking (updating and then undoing changes in the visited array).