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
$$O\left(mn\binom{m+n}{m}\right)$$
- Space complexity: No extra spaces needed (without considering recursive stack)
$$O(1)$$
Code
|
|