Nearest Exit from Entrance in Maze LeetCode solution in Python

1
class Solution:
2
def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
3
x, y = entrance
4
m, n, infi = len(maze), len(maze[0]), int(1e5)
5
reached = lambda p, q: (not p == x or not q == y) and (
6
p == 0 or q == 0 or p == m - 1 or q == n - 1
7
)
8

9
@lru_cache(None)
10
def dfs(i, j):
11
if i < 0 or j < 0 or i == m or j == n or maze[i][j] == "+":
12
return infi
13
if reached(i, j):
14
return 0
15
maze[i][j] = "+"
16
ans = 1 + min(dfs(i + 1, j), dfs(i - 1, j), dfs(i, j + 1), dfs(i, j - 1))
17
maze[i][j] = "."
18
return ans
19

20
ans = dfs(x, y)
21
return -1 if ans >= infi else ans

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0