题目:简单题
有 n 个房间,房间按从 0 到 n - 1 编号。最初,除 0 号房间外的其余所有房间都被锁住。你的目标是进入所有的房间。然而,你不能在没有获得钥匙的时候进入锁住的房间。
当你进入一个房间,你可能会在里面找到一套不同的钥匙,每把钥匙上都有对应的房间号,即表示钥匙可以打开的房间。你可以拿上所有钥匙去解锁其他房间。
给你一个数组 rooms 其中 rooms[i] 是你进入 i 号房间可以获得的钥匙集合。如果能进入 所有 房间返回 true,否则返回 false。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/keys-and-rooms
思路:
本题是有向图的形式,就是有单一的方向性,只能由谁到谁;
DFS和BFS的复习,深度优先和广度优先在二叉树中已经学习了很久,需要复习!
DFS和栈关联性很大,递归又隐含了方法栈的调用;所有DFS通常用递归实现!
BFS需要使用队列实现,一层一层的遍历!Queue
代码:
1)DFS实现:递归
class Solution {
int num = 0;
boolean flag[];
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
//深度优先DFS,看是否将所有的房间都进入
//遍历链表
num = 0;//记录遍历的房间数
flag = new boolean[rooms.size()];
dfs(rooms,0);
return num == rooms.size();
}
//x表示房间号
public void dfs(List<List<Integer>> rooms,int x){
//一次dfs就表示进来一间房
num++;
flag[x] = true;//表示进入过,不用再进入
for(int i : rooms.get(x)){//遍历进入x房间后拿到的钥匙,循环中的都是可以进入的房间
if(!flag[i]){
//没进入过就进入,进入过的不再计数,每个房间进入一次
dfs(rooms,i);
}
}
}
}
2)BFS:队列
class Solution {
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
int num = 0;
boolean flag[] = new boolean[rooms.size()];
Queue<Integer> queue = new LinkedList<>();
queue.offer(0);
flag[0] = true;
while(!queue.isEmpty()){
//出来就计数!
int index = queue.poll();
num++;
//往队列里加,就说明要进!就要设置为true;
for(int i : rooms.get(index)){
if(!flag[i]){
queue.offer(i);
flag[i] = true;
}
}
}
return num == rooms.size();
}
}