From 53af70278520e78a63fc5032d2cc27a613fae433 Mon Sep 17 00:00:00 2001 From: Shyam-Chen Date: Sun, 8 Sep 2024 17:04:42 +0800 Subject: [PATCH] 203rd Commit --- README.md | 14 +++++++----- .../canVisitAllRooms.test.ts | 8 +++++++ .../841. Keys and Rooms/canVisitAllRooms.ts | 22 +++++++++++++++++++ 3 files changed, 38 insertions(+), 6 deletions(-) create mode 100644 src/page-8/841. Keys and Rooms/canVisitAllRooms.test.ts create mode 100644 src/page-8/841. Keys and Rooms/canVisitAllRooms.ts diff --git a/README.md b/README.md index 34c0e8c..9569b9d 100644 --- a/README.md +++ b/README.md @@ -201,12 +201,14 @@ Ace Coding Interview with 75 Qs [700]: ./src/page-7/700.%20Search%20in%20a%20Binary%20Search%20Tree/searchBST.ts [450]: ./src/page-5/450.%20Delete%20Node%20in%20a%20BST/deleteNode.ts -| Graphs - DFS | | | -| ------------------------------------------------------------ | -------- | ------ | -| 841. Keys and Rooms | Solution | Medium | -| 547. Number of Provinces | Solution | Medium | -| 1466. Reorder Routes to Make All Paths Lead to the City Zero | Solution | Medium | -| 399. Evaluate Division | Solution | Medium | +| Graphs - DFS | | | +| ------------------------------------------------------------ | --------------- | ------ | +| 841. Keys and Rooms | [Solution][841] | Medium | +| 547. Number of Provinces | Solution | Medium | +| 1466. Reorder Routes to Make All Paths Lead to the City Zero | Solution | Medium | +| 399. Evaluate Division | Solution | Medium | + +[841]: ./src/page-8/841.%20Keys%20and%20Rooms/canVisitAllRooms.ts | Graphs - BFS | | | | ---------------------------------------- | -------- | ------ | diff --git a/src/page-8/841. Keys and Rooms/canVisitAllRooms.test.ts b/src/page-8/841. Keys and Rooms/canVisitAllRooms.test.ts new file mode 100644 index 0000000..5bd1926 --- /dev/null +++ b/src/page-8/841. Keys and Rooms/canVisitAllRooms.test.ts @@ -0,0 +1,8 @@ +import { canVisitAllRooms } from './canVisitAllRooms'; + +describe('841. Keys and Rooms', () => { + test('canVisitAllRooms', () => { + expect(canVisitAllRooms([[1], [2], [3], []])).toBe(true); + expect(canVisitAllRooms([[1, 3], [3, 0, 1], [2], [0]])).toBe(false); + }); +}); diff --git a/src/page-8/841. Keys and Rooms/canVisitAllRooms.ts b/src/page-8/841. Keys and Rooms/canVisitAllRooms.ts new file mode 100644 index 0000000..e10d33e --- /dev/null +++ b/src/page-8/841. Keys and Rooms/canVisitAllRooms.ts @@ -0,0 +1,22 @@ +type CanVisitAllRooms = (rooms: number[][]) => boolean; + +/** + * Accepted + */ +export const canVisitAllRooms: CanVisitAllRooms = (rooms) => { + const visited = new Set(); + + function dfs(room: number) { + visited.add(room); + + for (const key of rooms[room]) { + if (!visited.has(key)) { + dfs(key); + } + } + } + + dfs(0); + + return visited.size === rooms.length; +};