原题链接:Leetcode 841. 钥匙和房间
DFS
class Solution {
public:
vector<int> visit;
vector<vector<int>> adj;
int num=0;
void dfs(int i)
{
visit[i]=1;
num++;
for(auto x:adj[i])
{
if(!visit[x]) dfs(x);
}
}
bool canVisitAllRooms(vector<vector<int>>& rooms) {
int n=rooms.size();
visit.resize(n);
adj.resize(n);
for(int i=0;i<n;i++)
{
for(auto x:rooms[i]) adj[i].push_back(x);
}
dfs(0);
return num==n;
}
};
BFS
class Solution {
public:
bool canVisitAllRooms(vector<vector<int>>& rooms) {
int n=rooms.size();
vector<int> visit;
vector<vector<int>> adj;
visit.resize(n);
adj.resize(n);
for(int i=0;i<n;i++)
{
for(auto x:rooms[i]) adj[i].push_back(x);
}
queue<int> q;
q.push(0);
visit[0]=1;
int num=0;
while(!q.empty())
{
int i=q.front();
q.pop(); num++;
for(auto x:adj[i])
{
if(!visit[x])
{
q.push(x);
visit[x]=1;
}
}
}
return num==n;
}
};