leetcode841 钥匙和房间
//v1.0 深度优先搜索
class Solution {
boolean[] visited;
int num=0;
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
int size = rooms.size();
visited = new boolean[size];
dfs(rooms,0);
return size==num;
}
public void dfs(List<List<Integer>> rooms, int room){
visited[room] = true;
num++;
for(int i:rooms.get(room)){
if(!visited[i]){
dfs(rooms,i);
}
}
}
}
//v2.0 广度优先搜索
class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
int roomNum = rooms.size();
int num=0;
boolean[] visited = new boolean[roomNum];
Queue<Integer> queue = new LinkedList<Integer>();
queue.offer(0);
visited[0] = true;
while(!queue.isEmpty()){
int size = queue.size();
for(int i=0;i<size;i++){
num++;
int temp = queue.poll();
for(int room:rooms.get(temp)){
if(!visited[room]){
visited[room] = true;
queue.offer(room);
}
}
}
}
return roomNum == num;
}
}