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

[12/31] 980. Unique Paths III

컨텐츠 정보

본문

You are given an m x n integer array grid where grid[i][j] could be:

  • 1 representing the starting square. There is exactly one starting square.
  • 2 representing the ending square. There is exactly one ending square.
  • 0 representing empty squares we can walk over.
  • -1 representing obstacles that we cannot walk over.

Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.

 

Example 1:

Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
Output: 2
Explanation: We have the following two paths: 
1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)
2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)

Example 2:

Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]]
Output: 4
Explanation: We have the following four paths: 
1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)
2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)
3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)
4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)

Example 3:

Input: grid = [[0,1],[2,0]]
Output: 0
Explanation: There is no path that walks over every empty square exactly once.
Note that the starting and ending square can be anywhere in the grid.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 20
  • 1 <= m * n <= 20
  • -1 <= grid[i][j] <= 2
  • There is exactly one starting cell and one ending cell.
Accepted
163.4K
Submissions
200K
Acceptance Rate
81.7%
태그 ,

관련자료

댓글 1

학부유학생님의 댓글

  • 익명
  • 작성일
class Solution:
    def uniquePathsIII(self, grid: List[List[int]]) -> int:
        ROW, COL = len(grid), len(grid[0])
        path = set()

        start = (0,0)
        goal = (0,0)
        obstacles = 0

        for row in range(ROW):
            for col in range(COL):
                if grid[row][col] == 2:
                    goal = (row, col)
                elif grid[row][col] == -1:
                    obstacles += 1
                elif grid[row][col] == 1:
                    start = (row, col)
        res = 0
        directions = [(0,1),(1,0),(-1,0),(0,-1)]

        def dfs(r, c):
            path.add((r,c))
            if len(path) == ROW*COL - obstacles and (r,c) == goal:
                nonlocal res
                res += 1
            else:
                for rd, cd in directions:
                    nr, nc = r+rd, c+cd
                    if 0<=nr<ROW and 0<=nc<COL and grid[nr][nc] != -1 and (nr, nc) not in path:
                        dfs(nr, nc)
            path.remove((r,c))
        
        dfs(start[0], start[1])
        return res
전체 404 / 3 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 889 명
  • 오늘 방문자 4,431 명
  • 어제 방문자 6,975 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,536 명
알림 0