Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1197f44

Browse files
Added medium problem.
1 parent 92126a2 commit 1197f44

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

‎Leetcode/medium/keys-and-rooms.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
# KEYS AND ROOMS
3+
4+
There are N rooms and you start in room 0. Each room has a distinct number in 0, 1, 2, ..., N-1, and each room may have some keys to access the next room.
5+
6+
Formally, each room i has a list of keys rooms[i], and each key rooms[i][j] is an integer in [0, 1, ..., N-1] where N = rooms.length. A key rooms[i][j] = v opens the room with number v.
7+
8+
Initially, all the rooms start locked (except for room 0).
9+
10+
You can walk back and forth between rooms freely.
11+
12+
Return true if and only if you can enter every room.
13+
14+
Example 1:
15+
16+
Input: [[1],[2],[3],[]]
17+
Output: true
18+
Explanation:
19+
We start in room 0, and pick up key 1.
20+
We then go to room 1, and pick up key 2.
21+
We then go to room 2, and pick up key 3.
22+
We then go to room 3. Since we were able to go to every room, we return true.
23+
Example 2:
24+
25+
Input: [[1,3],[3,0,1],[2],[0]]
26+
Output: false
27+
Explanation: We can't enter the room with number 2.
28+
Note:
29+
30+
1 <= rooms.length <= 1000
31+
0 <= rooms[i].length <= 1000
32+
The number of keys in all rooms combined is at most 3000.
33+
"""
34+
35+
class Solution:
36+
def canVisitAllRooms(self, rooms):
37+
#graph = [[] for i in range(len(rooms))]
38+
#for neighbor
39+
visited = set()
40+
self.dfs(rooms, 0, visited)
41+
return len(visited) == len(rooms)
42+
43+
def dfs(self, rooms, current, visited):
44+
if current in visited:
45+
return
46+
47+
visited.add(current)
48+
for neighbor in rooms[current]:
49+
self.dfs(rooms, neighbor, visited)
50+
51+
return

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /