From 0df65e062882245b95f957514f2d17c51e2c9566 Mon Sep 17 00:00:00 2001 From: anjali9811 <72162196+anjali9811@users.noreply.github.com> Date: Thu, 1 Oct 2020 01:10:53 +0530 Subject: [PATCH] Add files via upload --- keys and rooms.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 keys and rooms.cpp diff --git a/keys and rooms.cpp b/keys and rooms.cpp new file mode 100644 index 0000000..85419e3 --- /dev/null +++ b/keys and rooms.cpp @@ -0,0 +1,23 @@ +class Solution { + public boolean canVisitAllRooms(List> rooms) { + boolean[] seen = new boolean[rooms.size()]; + seen[0] = true; + Stack stack = new Stack(); + stack.push(0); + + //At the beginning, we have a todo list "stack" of keys to use. + //'seen' represents at some point we have entered this room. + while (!stack.isEmpty()) { // While we have keys... + int node = stack.pop(); // Get the next key 'node' + for (int nei: rooms.get(node)) // For every key in room # 'node'... + if (!seen[nei]) { // ...that hasn't been used yet + seen[nei] = true; // mark that we've entered the room + stack.push(nei); // add the key to the todo list + } + } + + for (boolean v: seen) // if any room hasn't been visited, return false + if (!v) return false; + return true; + } +}