From 7d11733da7c396e96abebf6bf8e5debc8d1e1300 Mon Sep 17 00:00:00 2001 From: wang2jun <91008685+wang2jun@users.noreply.github.com> Date: Sat, 29 Oct 2022 14:17:54 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20841=E9=92=A5=E5=8C=99?= =?UTF-8?q?=E5=92=8C=E6=88=BF=E9=97=B4=20TS=20=EF=BC=88BFS=EF=BC=89?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 841钥匙和房间 TS (BFS) 代码 --- problems/0841.钥匙和房间.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) 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); +} +``` + +