class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
ans = 0
def travel(x, y, gold, visited):
nonlocal ans
if x >= 0 and y >= 0 and x < m and y < n and (x, y) not in visited and grid[x][y]:
visited.add((x, y))
val = grid[x][y]
gold += grid[x][y]
for a, b in ((1, 0), (-1, 0), (0, -1), (0, 1)):
travel(x + a, y + b, gold, visited)
visited.remove((x, y))
else:
ans = max(ans, gold)
for i in range(m):
for j in range(n):
travel(i, j, 0, set())
return ans