diff --git a/problems/0841.钥匙和房间.md b/problems/0841.钥匙和房间.md index 0233a710..5556922c 100644 --- a/problems/0841.钥匙和房间.md +++ b/problems/0841.钥匙和房间.md @@ -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); +} +``` + +