From 5f2a715ebd68fcb47705d01b14a75ca353ced001 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 9 Aug 2024 00:17:56 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB841.=20Keys=20and=20Rooms?= =?UTF-8?q?=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- go/keys-and-rooms.go | 48 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 go/keys-and-rooms.go diff --git a/go/keys-and-rooms.go b/go/keys-and-rooms.go new file mode 100644 index 0000000..4a673d1 --- /dev/null +++ b/go/keys-and-rooms.go @@ -0,0 +1,48 @@ +package main + +import ( + arraystack "github.com/emirpasic/gods/v2/stacks/arraystack" +) + +type DFSEntry struct { + room int + index int +} + +func (e *DFSEntry) Next() DFSEntry { + return DFSEntry{room: e.room, index: e.index + 1} +} + +func canVisitAllRooms(rooms [][]int) bool { + s := arraystack.New[DFSEntry]() + s.Push(DFSEntry{room: 0, index: 0}) + + visited := make([]bool, len(rooms)) + visited[0] = true + + for !s.Empty() { + key, _ := s.Pop() + + if key.index >= len(rooms[key.room]) { + continue + } + + s.Push(key.Next()) + + unlockedRoom := rooms[key.room][key.index] + if visited[unlockedRoom] { + continue + } + + visited[unlockedRoom] = true + s.Push(DFSEntry{room: unlockedRoom, index: 0}) + } + + for _, unlocked := range visited { + if !unlocked { + return false + } + } + + return true +}