728x90
▶841 - Keys and Rooms
▶문제
There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.
Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.
▶예제
Input: rooms = [[1],[2],[3],[]]
Output: true
Explanation:
We visit room 0 and pick up key 1.
We then visit room 1 and pick up key 2.
We then visit room 2 and pick up key 3.
We then visit room 3.
Since we were able to visit every room, we return true.
Input: rooms = [[1,3],[3,0,1],[2],[0]]
Output: false
Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.
▶풀이
dfs를 이용해서 탐색으로 풀었다.
만약에 갈 수 없는 노드가 있다면 visit에 0이 남아 있을 거다.
그렇게 판단해주었다.
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
def dfs(node):
if visit[node] == 1:
return
visit[node] = 1
for room in rooms[node]:
if visit[room] == 1:
continue
dfs(room)
visit = [0 for _ in range(len(rooms))]
dfs(0)
if 0 in visit:
return False
return True
728x90
'LeetCode' 카테고리의 다른 글
[LeetCode] Medium - 309 Best Time to Buy and Sell Stock with Cooldown (1) | 2022.12.23 |
---|---|
[LeetCode] Medium - 886 Possible Bipartition (0) | 2022.12.21 |
[LeetCode] Medium - 50 Pow(x, n) (0) | 2022.12.19 |
[LeetCode] Easy - 1971 Find if Path Exists in Graph (0) | 2022.12.19 |
[LeetCode] Medium - 380 Insert Delete GetRandom O(1) (0) | 2022.12.18 |