- Today
- Total
작심삼일
[LeetCode] 1926 | Nearest Exit from Entrance in Maze | Python 본문
문제 링크: https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/
문제
You are given an m x n matrix maze (0-indexed) with empty cells (represented as '.') and walls (represented as '+'). You are also given the entrance of the maze, where entrance = [entrancerow, entrancecol] denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the entrance. An exit is defined as an empty cell that is at the border of the maze. The entrance does not count as an exit.
Return the number of steps in the shortest path from the entrance to the nearest exit, or -1 if no such path exists.
조건
- maze.length == m
- maze[i].length == n
- 1 <= m, n <= 100
- maze[i][j] is either '.' or '+'.
- entrance.length == 2
- 0 <= $entrance_{row}$ < m
- 0 <= $entrance_{col}$ < n
- entrance will always be an empty cell.
내 풀이
BFS를 이용한다.
방문한 곳들을 벽으로 바꾸면서(maze[y][x] = '+') 방문 여부를 저장한다.
코드
class Solution:
def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
H, W = len(maze), len(maze[0])
y, x = entrance
queue = deque()
queue.append((y, x, 0))
maze[y][x] = '+'
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def is_exit(y, x):
return True if x == 0 or x == W-1 or y == 0 or y == H-1 else False
while queue:
y, x, ans = queue.popleft()
for t in range(4):
newY, newX = y+dy[t], x+dx[t]
if 0 <= newY < H and 0 <= newX < W and maze[newY][newX] == '.':
if is_exit(newY, newX):
return ans+1
maze[newY][newX] = '+'
queue.append((newY, newX, ans+1))
return -1
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 2225 | Find Players With Zero or One Losses (0) | 2022.11.28 |
---|---|
[LeetCode] 36 | Valid Sudoku | Python (0) | 2022.11.23 |
[LeetCode] 223 | Rectangle Area | Python (0) | 2022.11.17 |
[LeetCode] 374 | Guess Number Higher or Lower | Python (0) | 2022.11.16 |
[LeetCode] 947 | Most Stones Removed with Same Row or Column | Python (0) | 2022.11.14 |