Skip to content

Commit fbc50c0

Browse files
Merge pull request youngyangyang04#1722 from wang2jun/master
添加 841钥匙和房间 TS (BFS)代码
2 parents 0ad33e5 + 7d11733 commit fbc50c0

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

problems/0841.钥匙和房间.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,34 @@ var canVisitAllRooms = function(rooms) {
387387
```
388388

389389

390+
### TypeScript
391+
```ts
392+
// BFS
393+
// rooms :就是一个链接表 表示的有向图
394+
// 转换问题就是,一次遍历从 0开始 能不能 把所有的节点访问了,实质问题就是一个
395+
// 层序遍历
396+
function canVisitAllRooms(rooms: number[][]): boolean {
397+
const n = rooms.length;
398+
// cnt[i] 代表节点 i 的访问顺序, cnt[i] = 0, 代表没被访问过
399+
let cnt = new Array(n).fill(0);
400+
let queue = [0];
401+
cnt[0]++;
402+
while (queue.length > 0) {
403+
const from = queue.shift();
404+
for (let i = 0; i < rooms[from].length; i++) {
405+
const to = rooms[from][i];
406+
if (cnt[to] == 0) {
407+
queue.push(to);
408+
cnt[to]++;
409+
}
410+
}
411+
}
412+
// 只要其中有一个节点 没被访问过,那么就返回 false
413+
return cnt.every((item) => item != 0);
414+
}
415+
```
416+
417+
390418
<p align="center">
391419
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
392420
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>

0 commit comments

Comments
 (0)