From 7a4057066a52a68b60e1c19670a5f21b5ffa716c Mon Sep 17 00:00:00 2001 From: StriveDD Date: Thu, 2 Mar 2023 11:15:07 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0841.=E9=92=A5=E5=8C=99?= =?UTF-8?q?=E5=92=8C=E6=88=BF=E9=97=B4=E7=9A=84Java=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E7=9A=84BFS=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0841.钥匙和房间.md | 43 ++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/problems/0841.钥匙和房间.md b/problems/0841.钥匙和房间.md index a973ab56..00263cac 100644 --- a/problems/0841.钥匙和房间.md +++ b/problems/0841.钥匙和房间.md @@ -273,6 +273,48 @@ class Solution { return true; } } + +// 广度优先搜索 +class Solution { + public boolean canVisitAllRooms(List> rooms) { + boolean[] visited = new boolean[rooms.size()]; // 用一个 visited 数据记录房间是否被访问 + visited[0] = true; + Queue 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> rooms) { + int count = 1; // 用来记录可以被访问的房间数目,因为初始状态下 0 号房间可以被访问,所以置为 1 + boolean[] visited = new boolean[rooms.size()]; // 用一个 visited 数据记录房间是否被访问 + visited[0] = true; // 第 0 个房间标记为已访问 + Queue 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 { +