classSolution: defgetMaximumGold(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) defdfs(x, y): res = 0 origin = grid[x][y] # backup grid[x][y] = 0# mark as visited for nx, ny in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]: if0 <= nx < m and0 <= ny < n and grid[nx][ny] != 0: res = max(res, dfs(nx, ny)) grid[x][y] = origin # backtracking return res + origin ans = 0 for i inrange(m): for j inrange(n): if grid[i][j] != 0: ans = max(ans, dfs(i, j)) return ans
classSolution { public: int m, n; int DIR[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; intdfs(vector<vector<int>>& grid, int x, int y){ int res = 0; int origin = grid[x][y]; // backup grid[x][y] = 0; // mark as visited for (int k = 0; k < 4; k++) { int nx = x + DIR[k][0], ny = y + DIR[k][1]; if (0 <= nx && nx < m && 0 <= ny && ny < n && grid[nx][ny] != 0) { res = max(res, dfs(grid, nx, ny)); } } grid[x][y] = origin; // backtracking return res + origin; } intgetMaximumGold(vector<vector<int>>& grid){ m = grid.size(), n = grid[0].size(); int ans = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] != 0) { ans = max(ans, dfs(grid, i, j)); } } } return ans; } };