1219. Path with Maximum Gold

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]:
                # Mark as visited
                visited.add((x, y))

                val = grid[x][y]                      
                gold += grid[x][y]

                # Top, bottom, left, right
                for a, b in ((1, 0), (-1, 0), (0, -1), (0, 1)):
                    travel(x + a, y + b, gold, visited)

                # Remove from visited, to explore again
                visited.remove((x, y))
            else:
                ans = max(ans, gold)  

        # Find all posibilities, considering every point as a start
        for i in range(m):
            for j in range(n):
                travel(i, j, 0, set())

        return ans