本题其实是求DFS或BFS后,判断访问过的长度是否与rooms的长度相等:若相等,则为True;否则,为False。
方法1:DFS,递归
就是标准的DFS,可以套用模板:数据结构和算法 从0到1:图的深度优先搜索DFS,注意本题只能从0号房间开始,题中有说明
代码如下:
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
#DFS
n = len(rooms)
self.res = []
self.dfs(0,rooms)
return len(self.res) == n
def dfs(self,begin,rooms):
if begin not in self.res:
self.res.append(begin)
for key in rooms[begin]:
if key not in self.res:
self.dfs(key,rooms)
或者:
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
#DFS,递归
self.visited = {0}
self.dfs(0,rooms)
return len(self.visited) == len(rooms)
def dfs(self,index,rooms):
self.visited.add(index)
for key in rooms[index]:
if key not in self.visited:
self.dfs(key,rooms)
DFS迭代:
这需要栈来实现
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
#DFS,迭代
visited,stack = {0},[0]
while stack:
index = stack.pop()
for key in rooms[index]:
if key not in visited:
visited.add(key)
stack.append(key)
return len(visited) == len(rooms)
方法2:BFS
需要借助队列实现
可以参考模板:数据结构和算法 从0到1:图的广度优先搜索BFS
代码如下:
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
#BFS
visited,queue = {0},[0]
while queue:
index = queue.pop(0)
for key in rooms[index]:
if key not in visited:
visited.add(key)
queue.append(key)
return len(visited) == len(rooms)
方法1和方法2:
时间复杂度:O(N+M),N为房间的数量,M为所有房间中钥匙数量的总数
空间复杂度:O(N),N为房间的数量