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.