파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 10. 30. 23:50

https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/

 

Shortest Path in a Grid with Obstacles Elimination - 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

최단거리?! 와우....
일단 풀기전에 포긔s..

class Solution:
    def shortestPath(self, grid: List[List[int]], k: int) -> int:
        m, n = len(grid), len(grid[0])
        
        if k >= m + n -2:
            return m + n - 2
        
        dq = deque([(0, 0, k, 0)])
        visited = set()
        
        while dq:
            i, j, k, s = dq.popleft()
            if (i, j) == (m-1, n-1):
                return s
            
            for ii, jj in [(i+1,j), (i-1,j), (i, j+1), (i, j-1)]:
                if 0 <= ii < m and 0 <= jj <n and k >= grid[ii][jj]:
                    step = (ii, jj, k-grid[ii][jj], s+1)
                    if step[0:3] not in visited:
                        visited.add(step[0:3])
                        dq.append(step)
        
        return -1
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.11.01
Today's Challenge  (0) 2022.10.31
Today's Challenge  (0) 2022.10.29
Today's Challenge  (0) 2022.10.28
Today's Challenge  (0) 2022.10.27
Comments