Keys and Rooms
LeetCode 841 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
BFS from room 0 over key edges.
నేను Keys and Rooms (LeetCode 841) ను ఇలా పరిష్కరించాను — Graph Fundamentals / DFS ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Rooms are nodes and keys are edges. Starting from room 0, BFS through every room you can unlock; you succeed if every room gets visited.
Approach
- 1
Mark room 0 visited and enqueue it.
- 2
For each key in a room, visit unvisited rooms.
- 3
Return all(visited).
నేను ఎలా పరిష్కరించాను
BFS reachabilityPythonO(N+K) time
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
"""
0 - [1]
1 - [2]
2 - [3]
3 - []
with the key at room 0 we can visit room 1
0 -> 1 [adj list]
0 has keys- 1,3 so from 0 we can visit 1,3
"""
n = len(rooms)
visited = [False]*n
visited[0]=True
q = deque([0])
while q:
node = q.popleft()
for adj_node in rooms[node]:
if visited[adj_node]==False:
visited[adj_node]=True
q.append(adj_node)
return all(visited)Keys and Rooms — తరచూ అడిగే ప్రశ్నలు
Keys and Rooms వెనుక ఉన్న intuition ఏమిటి?
Rooms are nodes and keys are edges. Starting from room 0, BFS through every room you can unlock; you succeed if every room gets visited.
Keys and Rooms (LeetCode 841) ను ఎలా పరిష్కరించాలి?
1. Mark room 0 visited and enqueue it. 2. For each key in a room, visit unvisited rooms. 3. Return all(visited).
Keys and Rooms యొక్క time, space complexity ఎంత?
Time: O(N + K). Space: O(N). (Accepted approach: BFS reachability.)
Keys and Rooms లో సాధారణ పొరపాట్లు ఏమిటి?
A key to an already-visited room is ignored.