思路:深度优先遍历即可。
/**
* @Auther: Mason
* @Date: 2020/07/20/9:28
* @Description:
*/
public class Solution {
public int count; // 计数有几个房间现在可以打开
public boolean[] mark; // 标记某个房间是否可以被打开。
public int size; // 屋子的总个数。
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
count = 1;
size = rooms.size();
mark = new boolean[size];
mark[0] = true;
dfs(rooms, 0);
return count == size;
}
/**
* @param rooms
* @param i 房子的序号
*/
private void dfs(List<List<Integer>> rooms, int i) {
if (count == size) return;
// 第i号房子在mark中已经被更新了。
List<Integer> keys = rooms.get(i);
for (Integer key : keys) {
if (!mark[key]) {
mark[key] = true;
count++;
dfs(rooms, key);
}
}
}
}