Problem
A competitive runner would like to create a route that starts and ends at his house, with the condition that the route goes entirely uphill at first, and then entirely downhill.
Given a dictionary of places of the form {location: elevation}, and a dictionary mapping paths between some of these locations to their corresponding distances, find the length of the shortest route satisfying the condition above. Assume the runner’s home is location 0.
Examples
Example 1:
| |
Solution
Method 1 - DFS
Here’s an overall approach to solve the problem:
- Graph Representation:
- Use the
elevationsdictionary to store the elevation of each location. - Use the
pathsdictionary to represent edges between the locations with their distances.
- Use the
- Finding Valid Paths:
- Use Depth-First Search (DFS) to explore possible uphill routes from the home location
0. - For each uphill path found, use DFS to search for a valid downhill path back to the home location
0.
- Use Depth-First Search (DFS) to explore possible uphill routes from the home location
- Tracking the Shortest Path:
- Track the shortest valid path satisfying the constraints.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(E.V), whereEis number of edges, andVis number of vertices- In the worst case, the algorithm explores all possible paths from the home location. Given that there are
Vlocations (vertices) andEpaths (edges), the DFS explores each edge multiple times. - For each node, we examine all edges, leading to a complexity component of
O(E).
- In the worst case, the algorithm explores all possible paths from the home location. Given that there are
- 🧺 Space complexity:
O(V), for using recursion stack and for usingvisitedset.