Skip to content

Commit a9277b8

Browse files
committed
Create 1926-NearestExitFromEntranceInMaze.py
1 parent 4d053c7 commit a9277b8

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#!/usr/bin/env python3
2+
"""
3+
CREATED AT: 2022-11-21
4+
5+
URL: https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/?envType=study-plan&id=graph-i
6+
7+
GITHUB: https://github.com/Jiezhi/myleetcode
8+
9+
FileName: 1926-NearestExitFromEntranceInMaze
10+
11+
Difficulty: Medium
12+
13+
Desc:
14+
15+
Tag:
16+
17+
See:
18+
19+
"""
20+
from tool import *
21+
22+
23+
class Solution:
24+
def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
25+
"""
26+
Runtime: 968 ms, faster than 82.11%
27+
Memory Usage: 14.4 MB, less than 86.37%
28+
29+
maze.length == m
30+
maze[i].length == n
31+
1 <= m, n <= 100
32+
maze[i][j] is either '.' or '+'.
33+
entrance.length == 2
34+
0 <= entrancerow < m
35+
0 <= entrancecol < n
36+
entrance will always be an empty cell.
37+
"""
38+
m, n = len(maze), len(maze[0])
39+
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
40+
maze[entrance[0]][entrance[1]] = '+'
41+
dq = deque([(entrance[0], entrance[1], 0)])
42+
while dq:
43+
x, y, step = dq.popleft()
44+
if (x == 0 or x == m - 1 or y == 0 or y == n - 1) and step != 0:
45+
return step
46+
for dx, dy in dirs:
47+
nx, ny = x + dx, y + dy
48+
if not 0 <= nx < m or not 0 <= ny < n or maze[nx][ny] == '+':
49+
continue
50+
maze[nx][ny] = '+'
51+
dq.append((nx, ny, step + 1))
52+
return -1
53+
54+
55+
def test():
56+
assert Solution().nearestExit(maze=[["+", "+", ".", "+"], [".", ".", ".", "+"], ["+", "+", "+", "."]],
57+
entrance=[1, 2]) == 1
58+
assert Solution().nearestExit(maze=[["+", "+", "+"], [".", ".", "."], ["+", "+", "+"]], entrance=[1, 0]) == 2
59+
assert Solution().nearestExit(maze=[[".", "+"]], entrance=[0, 0]) == -1
60+
61+
62+
if __name__ == '__main__':
63+
test()

0 commit comments

Comments
 (0)