Keys and Rooms

최제원·2024년 7월 21일

algorithm

목록 보기
4/12
post-thumbnail

https://leetcode.com/problems/keys-and-rooms/description/

문제 이해

[0][0] 방에서 습득할수 있는 키를 바탕으로 시작하여 모든 방을 열수 있는지
탐색하는 문제

문제 포인트

배열 그래프 문제인데 dfs탐색으로 풀었다 key를 갖고 순차적으로 방에 진입한 후에
dfs가 모두 완료되면 더이상 배열을 순회하지 않고 return

제출 코드

from collections import deque

class Solution(object):
    def canVisitAllRooms(self, rooms):
        visited = [False] * len(rooms)
        queue = deque()

        queue.append(0)  # 0번 방에서 시작

        while queue:
            current_index = queue.popleft()
            if not visited[current_index]:  # 방문하지 않았다면
                visited[current_index] = True
                for key in rooms[current_index]:
                    if not visited[key]:  # 아직 방문하지 않은 방의 키라면
                        queue.append(key)

        return True if all(visited) else False
profile
Why & How

0개의 댓글