Given a matrix, whose element representing the number of golds. Find a path such that the sum is maximized and without crossing the grids that has not gold elements.
Intuition
Use backtracking to find all possible paths, and update the results.
Approach
We use two variables current and result to store results, current stores the sum of golds from start to current position, result stores the final result.
Complexity
- Time complexity: In worst case, each grid contains gold, for each position, there are $\binom{m+n}{m}$ possible paths, so the overall complexity is
- Space complexity: No extra spaces needed (without considering recursive stack)
Code
| |