广度优先搜索_钥匙和房间
841. 钥匙和房间 - 力扣(LeetCode)
算法描述
起始元素入队 查找队首元素的邻居节点 发现之后 入队 并且标记位已访问
接着 队首元素出队 一直循环 直到队列为空
#define maxn 10001
class Solution {
public:
void addEdge( vector<vector<int>>& table, vector<vector<int>>& rooms, int n){
for ( int i = 0; i < rooms.size(); ++i){
for ( int j : rooms[i])
table[i].push_back(j);
}
}
int bfs( vector<vector<int>>& table, int n, int visited[]){
queue<int> q;
q.push(0);
visited[0] = true;
int cnt = 0;
while ( !q.empty() ){
++cnt;
int u = q.front();
q.pop();
for ( int i = 0; i < table[u].size(); ++i ){
int j = table[u][i];
if ( !visited[j]){
q.push(j);
visited[j] = true;
}
}
}
return cnt;
}
bool canVisitAllRooms(vector<vector<int>>& rooms) {
int n = rooms.size();
vector< vector<int> > table(n);
int visited[maxn] = {0};
addEdge( table, rooms, n);
return bfs( table, n, visited) == n;
}
};