mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
添加841.钥匙和房间的Java版本的BFS代码
This commit is contained in:
@ -273,6 +273,48 @@ class Solution {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 广度优先搜索
|
||||
class Solution {
|
||||
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
|
||||
boolean[] visited = new boolean[rooms.size()]; // 用一个 visited 数据记录房间是否被访问
|
||||
visited[0] = true;
|
||||
Queue<Integer> queue = new ArrayDeque<>();
|
||||
queue.add(0); // 第 0 个房间标记为已访问
|
||||
while (!queue.isEmpty()) {
|
||||
int curKey = queue.poll();
|
||||
for (int key: rooms.get(curKey)) {
|
||||
if (visited[key]) continue;
|
||||
visited[key] = true;
|
||||
queue.add(key);
|
||||
}
|
||||
}
|
||||
for (boolean key: visited)
|
||||
if (!key) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 广度优先遍历(时间优化)
|
||||
class Solution {
|
||||
public boolean canVisitAllRooms(List<List<Integer>> rooms) {
|
||||
int count = 1; // 用来记录可以被访问的房间数目,因为初始状态下 0 号房间可以被访问,所以置为 1
|
||||
boolean[] visited = new boolean[rooms.size()]; // 用一个 visited 数据记录房间是否被访问
|
||||
visited[0] = true; // 第 0 个房间标记为已访问
|
||||
Queue<Integer> queue = new ArrayDeque<>();
|
||||
queue.add(0);
|
||||
while (!queue.isEmpty()) {
|
||||
int curKey = queue.poll();
|
||||
for (int key: rooms.get(curKey)) {
|
||||
if (visited[key]) continue;
|
||||
++count; // 每访问一个访问房间就让 count 加 1
|
||||
visited[key] = true;
|
||||
queue.add(key);
|
||||
}
|
||||
}
|
||||
return count == rooms.size(); // 如果 count 等于房间数目,表示能进入所有房间,反之不能
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### python3
|
||||
@ -417,3 +459,4 @@ function canVisitAllRooms(rooms: number[][]): boolean {
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
</a>
|
||||
|
||||
|
Reference in New Issue
Block a user