mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
添加 841钥匙和房间 TS (BFS)代码
添加 841钥匙和房间 TS (BFS) 代码
This commit is contained in:
@ -387,6 +387,34 @@ var canVisitAllRooms = function(rooms) {
|
|||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### TypeScript
|
||||||
|
```ts
|
||||||
|
// BFS
|
||||||
|
// rooms :就是一个链接表 表示的有向图
|
||||||
|
// 转换问题就是,一次遍历从 0开始 能不能 把所有的节点访问了,实质问题就是一个
|
||||||
|
// 层序遍历
|
||||||
|
function canVisitAllRooms(rooms: number[][]): boolean {
|
||||||
|
const n = rooms.length;
|
||||||
|
// cnt[i] 代表节点 i 的访问顺序, cnt[i] = 0, 代表没被访问过
|
||||||
|
let cnt = new Array(n).fill(0);
|
||||||
|
let queue = [0];
|
||||||
|
cnt[0]++;
|
||||||
|
while (queue.length > 0) {
|
||||||
|
const from = queue.shift();
|
||||||
|
for (let i = 0; i < rooms[from].length; i++) {
|
||||||
|
const to = rooms[from][i];
|
||||||
|
if (cnt[to] == 0) {
|
||||||
|
queue.push(to);
|
||||||
|
cnt[to]++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 只要其中有一个节点 没被访问过,那么就返回 false
|
||||||
|
return cnt.every((item) => item != 0);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
|
Reference in New Issue
Block a user