int delrow[4] = {-1, 0, 1, 0};
int delcol[4] = {0, 1, 0, -1};
void dfs(int row, int col, vector<vector<int>> &vis, vector<vector<int>> &grid, int ¤tSum, int &maxSum) {
int n = grid.size();
int m = grid[0].size();
vis[row][col] = 1;
currentSum += grid[row][col];
maxSum = max(maxSum, currentSum);
for (int i = 0; i < 4; i++) {
int nrow = row + delrow[i];
int ncol = col + delcol[i];
if (nrow >= 0 && nrow < n && ncol >= 0 && ncol < m && !vis[nrow][ncol] && grid[nrow][ncol] > 0) {
dfs(nrow, ncol, vis, grid, currentSum, maxSum);
}
}
// Backtrack
vis[row][col] = 0;
currentSum -= grid[row][col];
}
int maxGold(vector<vector<int>> &grid, int n, int m) {
int maxSum = 0;
vector<vector<int>> vis(n, vector<int>(m, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] > 0) {
int currentSum = 0;
dfs(i, j, vis, grid, currentSum, maxSum);
}
}
}
return maxSum;
}