The main problem comes down to finding a path between two nodes, if it exists. If the path exists, return the cumulative sums along the path as the result. Given the problem, it seems that we need to track the nodes where we come from. DFS (Depth-First Search), also known as the backtracking algorithm, will be applicable in this case.
Here is how the implementation will take place:
Build the graph using the city map list G_map.
Assign the cost to each edge while building the graph.
Once the graph is built, evaluate each driver’s path in the drivers list by searching for a path between the driver node and the user node.
Return the accumulated sum if the path exists. Otherwise, return -1.
Let’s look at the code for the solution: