-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Keys and Rooms #1
Comments
DFS 풀이각 방은 노드, 각 방에서 획득하는 열쇠 꾸러미는 간선들을 의미한다. DFS, BFS 시간 복잡도
func solution1_2(_ rooms: [[Int]]) -> Bool {
// 또는 set, dictionary 를 사용해서도 시간복잡도를 줄일 수 있다
var check = Array(repeating: false, count: rooms.count)
check[0] = true
dfs(0)
func dfs(_ roomNum: Int) {
check[roomNum] = true
for key in rooms[roomNum] {
if check[key] { continue }
dfs(key)
}
}
return !(check.filter({$0==false}).count > 0)
} |
BFS 풀이func solution(_ rooms: [[Int]]) -> Bool {
var check = Array(repeating: false, count: rooms.count)
var queue = [Int]()
queue.append(0)
check[0] = true
while(!queue.isEmpty) {
let current = queue.removeFirst()
for next in rooms[current] {
if check[next] { continue }
queue.append(next)
check[next] = true
}
}
return !(check.filter({ $0 == false} ).count > 0)
}
solution([[1],[2],[3],[]]) //true
solution([[1,3],[3,0,1],[2],[0]])//false |
❌ 틀린 접근 방법Union&Find
func solution1_3(_ rooms: [[Int]]) -> Bool {
var graph = Array(repeating: 0, count: rooms.count)
for i in 0..<rooms.count {
graph[i] = i
}
// 1. rooms 를 loop 돌면서 union(연결) 한다
for i in 0..<rooms.count {
for key in rooms[i] {
print(i, "->", key)
union(a: i, b: key)
}
}
//2.모든 노드가 연결되었는지 확인한다.
for i in 0..<rooms.count-1 {
let fa = find(i)
let fb = find(i+1)
if fa != fb { return false }
}
print(graph)
return true
func find(_ node: Int) -> Int {
if node == graph[node] { return node }
graph[node] = find(graph[node])
return graph[node]
}
func union(a: Int, b: Int) {
let fa = find(a)
let fb = find(b)
if fa != fb { graph[fa] = fb }
}
}
// 정답: false
solution1_3([[1],[],[0,3],[1]]) // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
문제
There are n rooms labeled from 0 to n - 1 and all the rooms are locked except for room 0. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.
Given an array rooms where rooms[i] is the set of keys that you can obtain if you visited room i, return true if you can visit all the rooms, or false otherwise.
제약조건
n == rooms.length
2 <= n <= 1000
0 <= rooms[i].length <= 1000
1 <= sum(rooms[i].length) <= 3000
0 <= rooms[i][j] < n
rooms[i]
are unique.The text was updated successfully, but these errors were encountered: