Sponsored
Sponsored
This approach utilizes backtracking and depth-first search (DFS) to explore all possible paths to collect the maximum gold. Start from each cell containing gold and perform DFS to explore in all four possible directions (up, down, left, right). During the search, keep track of the total gold collected. Use backtracking to unvisit a cell after exploring all potential paths from it.
Time complexity: O((m*n)^2) - In the worst-case scenario, each cell containing gold gets visited and backtracked.
Space complexity: O(m*n) - This results from recursive stack space and the grid modifications.
1#include <stdio.h>
2
3int dfs(int** grid, int m, int n, int x, int y) {
4 if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == 0)
5 return 0;
6
7 int originalGold = grid[x][y];
8 grid[x][y] = 0; // Mark as visited
9
10 int maxGold = 0;
11 int directions[4][2] = {{1,0}, {-1,0}, {0,1}, {0,-1}};
12 for (int i = 0; i < 4; ++i) {
13 maxGold = fmax(maxGold, dfs(grid, m, n, x + directions[i][0], y + directions[i][1]));
14 }
15
16 grid[x][y] = originalGold; // Backtrack
17 return originalGold + maxGold;
18}
19
20int getMaximumGold(int** grid, int gridSize, int* gridColSize) {
21 int maxGold = 0;
22 for (int i = 0; i < gridSize; ++i) {
23 for (int j = 0; j < gridColSize[i]; ++j) {
24 if (grid[i][j] > 0) {
25 maxGold = fmax(maxGold, dfs(grid, gridSize, gridColSize[i], i, j));
26 }
27 }
28 }
29 return maxGold;
30}
The C language implementation uses a recursive function 'dfs' to explore each valid path starting from a gold cell. It employs a grid to mark visited cells by setting their gold value to zero and restores them after backtracking is complete. This way, all potential paths can be explored to determine the path with the maximum gold.
This approach involves using dynamic programming with bit masking to track visited states and optimize the path of maximum gold collection. It systematically calculates the maximum gold that can be gathered by starting from each gold cell and considering valid moves while ensuring no cell is revisited.
Time complexity: O(2^(m*n) * m * n) given bitmask state examination.
Space complexity: O(2^(m*n) * m * n) due to DP storage needs for various path states.
1
The Python algorithm employs @functools.lru_cache to optimize the DP process, significantly reducing computation time through memoization techniques. This permits efficient path resolution by retaining repetitive calculations, yielding improved performance despite potential combinatorial explosion from bitmask exploration.