1219. Path with Maximum Gold

알고리즘 문제풀기 · 2019. 12. 4. 14:48

https://leetcode.com/problems/path-with-maximum-gold

 

Path with Maximum Gold - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

백트래킹 문제

 

경로를 리스트로 쓰는 경우보다 집합으로 쓰는것이 훨씬 편함.

grid를 가져가서 방문했다고 맵에 체크하는 것보다 인덱스를 가지고 집합에 저장해두면 훨씬 수월하다.

 

 

 

class Solution(object):
    
    def getMaximumGold(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        self.max_value = 0
    
        def recur(r,c, visited, grid, total):
            
            visited.add((r,c))
            
            total += grid[r][c]
            
            for (x,y) in ((r+1,c), (r-1,c), (r,c+1), (r,c-1)):
                
                if 0 <= x < len(grid) and 0 <= y < len(grid[0]) and grid[x][y] != 0 and (x,y) not in visited:
                    
                    recur(x,y, visited, grid, total)
                    visited.remove((x,y))                                        
                else:
                    
                    self.max_value = max(self.max_value, total)

        for i in range(0, len(grid), 1):
            
            for j in range(0, len(grid[0]), 1):
                
                if grid[i][j] != 0:
                
                    recur(i,j,set(),grid,0)                   

        return self.max_value

 

'알고리즘 문제풀기' 카테고리의 다른 글

300. Longest Increasing Subsequence  (0) 2019.12.05
1048. Longest String Chain  (0) 2019.12.05
988. Smallest String Starting From Leaf  (0) 2019.11.28
792. Number of Matching Subsequences  (0) 2019.11.27
392. Is Subsequence  (0) 2019.11.27