题目链接:Keys and Rooms - LeetCodehttps://leetcode.com/problems/keys-and-rooms/description/
解题思路:bfs
AC代码:(Accept)
class Solution {
public:
vector<int>vis;
queue<int>q;
bool canVisit(vector<vector<int>>& rooms){
vis[0]=1;
for(int i=0;i<rooms[0].size();i++){
q.push(rooms[0][i]);
}
while(!q.empty()){
int now=q.front();
q.pop();
vis[now]=1;
for(int i=0;i<rooms[now].size();i++){
if(!vis[rooms[now][i]]){
q.push(rooms[now][i]);
}
}
}
for(int i=0;i<rooms.size();i++){
if(!vis[i]){
return false;
}
}
return true;
}
bool canVisitAllRooms(vector<vector<int>>& rooms) {
int n=rooms.size();
vis.resize(n, 0);
return canVisit(rooms);
}
};