n == rooms.length
2 <= n <= 1000
0 <= rooms[i].length <= 1000
1 <= sum(rooms[i].length) <= 3000
0 <= rooms[i][j] < n
All the values of rooms[i] are unique.
class Solution:
def canVisitAllRooms(self, rooms) -> bool:
n = len(rooms)
visited = [False] * n
def dfs(cur_v, depth):
visited[cur_v] = True
# base case
if depth == n:
return
# distinct key가 없으면
if len(rooms[cur_v]) == 0:
return
else:
for g in rooms[cur_v]:
if (not visited[g]):
dfs(g, depth+1)
dfs(0, 1)
canVisit = True
for i in range(n):
if not visited[i]:
canVisit = False
break
return canVisit
class Solution:
def canVisitAllRooms(self, rooms) -> bool:
# graph가 곧 rooms
canVisit = True
n = len(rooms)
visited = [False] * n
# start_v
q = deque()
q.append(0)
visited[0] = True
count = 1
while q:
if count == n:
break
cur_v = q.popleft()
if len(rooms[cur_v]):
for next_v in rooms[cur_v]:
if not visited[next_v]:
visited[next_v] = True
count+=1
q.append(next_v)
else:
continue
# if any room is not visited
for v in visited:
if not v:
canVisit = False
return canVisit
1. 처음 코드 (잘못된 코드)
if len(rooms[cur_v]):
for next_v in rooms[cur_v]:
if not visited[next_v]:
visited[next_v] = True
count+=1
q.append(next_v)
###### 잘못된 코드 ######
else:
break # continue로 바꾸어주어야 한다.
########################
if __name__ == "__main__":
rooms = [[1,3],[1,4],[2,3,4,1],[],[4,3,2]]
solution = Solution()
canVisit = solution.canVisitAllRooms(rooms)
print("canVisit?: ", canVisit)
canVisit?: True