Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 841 · Graph Fundamentals / DFS

Keys and Rooms

LeetCode 841 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

BFS from room 0 over key edges.

நடுத்தரம்Depth-First SearchBreadth-First SearchGraph Theory
LeetCode இல் திற ↗

நான் 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. 1

    Mark room 0 visited and enqueue it.

  2. 2

    For each key in a room, visit unvisited rooms.

  3. 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.