파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 11. 21. 23:45

https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/

 

Nearest Exit from Entrance in Maze - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

BFS의 정석과 같은 문제

class Solution:
    def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
        rows, cols = len(maze), len(maze[0])
        dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
        
        start_row, start_col = entrance
        maze[start_row][start_col] = "+"
        
        qu = collections.deque()
        qu.append([start_row, start_col, 0])
        
        while qu:
            curr_row, curr_col, curr_distance = qu.popleft()
            
            for d in dirs:
                next_row = curr_row + d[0]
                next_col = curr_col + d[1]
                
                if 0 <= next_row < rows and 0 <= next_col < cols and maze[next_row][next_col] == '.':
                    if 0 == next_row or next_row == rows - 1 or 0 == next_col or next_col == cols - 1:
                        return curr_distance + 1
                    
                    maze[next_row][next_col] = '+'
                    qu.append([next_row, next_col, curr_distance + 1])
        
        return -1
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.11.23
Today's Challenge  (0) 2022.11.22
Today's Challenge  (0) 2022.11.20
Today's Challenge  (0) 2022.11.19
Today's Challenge  (0) 2022.11.18
Comments