题目
题解
也是一道图的题,把某个房间的钥匙想成 连接两个结点的有向边,组成一张有向图,问题即是求从0号结点出发能否到达所有结点
dfs
用dfs遍历图,统计可以到达的结点数目
(复习一下图的dfs写法,老不写都快忘了…
class Solution {
int count=0;
boolean[] vis;
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
int n=rooms.size();
vis=new boolean[n];
dfs(rooms,0);
return count==n;
}
public void dfs(List<List<Integer>> rooms,int r){
vis[r]=true;
count++;
//遍历其余未访问过的房间号
for(int i:rooms.get(r)){
if(!vis[i])
dfs(rooms,i);
}
}
}
时间复杂度: O ( n + m ) O(n+m) O(n+m),其中 n 是房间的数量,m 是所有房间中的钥匙数量的总数
空间复杂度: O ( n ) O(n) O(n)
bfs
使用队列进行广度优先搜索
class Solution {
int count=0;
boolean[] vis;
Queue<Integer>queue=new LinkedList<>();
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
int n=rooms.size();
vis=new boolean[n];
queue.offer(0);
vis[0]=true;
while(!queue.isEmpty()){
int r=queue.poll();
count++;
for(int i:rooms.get(r)){
if(!vis[i]){
queue.offer(i);
vis[i]=true;//一定要在入队时就将vis[i]置为true!否则会重复访问i
}
}
}
return count==n;
}
}
时间复杂度: O ( n + m ) O(n+m) O(n+m)
空间复杂度: O ( n ) O(n) O(n)