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

मी 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.