https://leetcode.com/problems/keys-and-rooms/
기본적인 DFS/BFS 코드를 응용하는 문제였습니다.
class Solution {
func canVisitAllRooms(_ rooms: [[Int]]) -> Bool {
var visited = Array(repeating: false, count: rooms.count)
visited[0] = true
func dfs (_ array: [Int]) {
for i in array {
if !visited[i] {
visited[i] = true
dfs(rooms[i])
}
}
}
dfs(rooms[0])
for i in visited {
if !i {
return false
}
}
return true
}
}
class Solution {
func canVisitAllRooms(_ rooms: [[Int]]) -> Bool {
var visited = Array(repeating: false, count: rooms.count)
var queue = [0]
visited[0] = true
func bfs (_ array: [Int]) {
while !queue.isEmpty {
let cur_room = queue.removeFirst()
for i in rooms[cur_room] {
if !visited[i] {
queue.append(i)
visited[i] = true
}
}
}
}
bfs(rooms[0])
for i in visited {
if !i {
return false
}
}
return true
}
}