Graph Theory-Revision

841. Keys and Rooms

In this question we are given a 2d array rooms, if we are at index i then one can move from room i to room arr[i], in this way, we can reach rooms, there are in total n rooms starting from 0 to n-1, in the end, we have to tell whether we reached all the rooms or not.

My approach to this question is

  1. we are already given adjacency list rooms, through which we can move to other rooms, we can solve this question using BFS and DFS both,

  2. I have used the BFS approach where I have stored 0 first in the queue and then using for each loop we can move to other rooms attached to that particular room and whichever room we have visited we will mark it as visited (vis[node]=1).

  3. In the end, we can check if any room is unvisited we can return false, otherwise return true.

 void isvisited(int node,vector<int>& vis,vector<vector<int>>& rooms)
    {
        vis[node]=1;
        queue<int> q;
        q.push(node);

        while(!q.empty())
        {
            int x=q.front();
            q.pop();

            for(auto it:rooms[x])
            {
                if(!vis[it])
                {
                    q.push(it);
                    vis[it]=1;
                }
            }

        }
    }
    bool canVisitAllRooms(vector<vector<int>>& rooms) 
    {
        int n=rooms.size();

        vector<int> vis(n,0);

        isvisited(0,vis,rooms);

        for(int i=0;i<vis.size();i++)
        {
            if(!vis[i])
            {
                return false;
            }
        }

        return true;
    }