엔지니어 게시판
LeetCode 솔루션 분류

[10/30] 1293. Shortest Path in a Grid with Obstacles Elimination

컨텐츠 정보

본문

You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step.

Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m - 1, n - 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1.

 

Example 1:

Input: grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]], k = 1
Output: 6
Explanation: 
The shortest path without eliminating any obstacle is 10.
The shortest path with one obstacle elimination at position (3,2) is 6. Such path is (0,0) -> (0,1) -> (0,2) -> (1,2) -> (2,2) -> (3,2) -> (4,2).

Example 2:

Input: grid = [[0,1,1],[1,1,1],[1,0,0]], k = 1
Output: -1
Explanation: We need to eliminate at least two obstacles to find such a walk.

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 40
  • 1 <= k <= m * n
  • grid[i][j] is either 0 or 1.
  • grid[0][0] == grid[m - 1][n - 1] == 0
Accepted
158,232
Submissions
347,737

관련자료

댓글 1

학부유학생님의 댓글

  • 익명
  • 작성일
Runtime: 1968 ms, faster than 20.02% of Python3 online submissions for Shortest Path in a Grid with Obstacles Elimination.
Memory Usage: 22.3 MB, less than 17.89% of Python3 online submissions for Shortest Path in a Grid with Obstacles Elimination.
from collections import deque
class Solution:
    def shortestPath(self, grid: List[List[int]], k: int) -> int:
        ROW, COL = len(grid), len(grid[0])
        
        queue = deque([(0,0,k,0)])
        visited = set((0,0,k))
        
        directions = [(0,1),(1,0), (0,-1),(-1,0)]
        
        while queue:
            r, c, curr_k, steps = queue.popleft()
            
            if (r,c) == (ROW-1, COL-1): return steps
            
            
            for rdir, cdir in directions:
                nr, nc = r+rdir, c+cdir
                
                if 0<=nr<ROW and 0<=nc<COL:
                    new_k = curr_k - grid[nr][nc]
                    if new_k >=0 and (nr,nc,new_k) not in visited:
                        visited.add((nr,nc,new_k))
                        queue.append((nr,nc,new_k,steps+1))
                        
            
        return -1
전체 410 / 1 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 646 명
  • 오늘 방문자 6,155 명
  • 어제 방문자 9,517 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,599 명
알림 0