문제 : https://leetcode.com/problems/keys-and-rooms/
Keys and Rooms - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
풀이방법
- 큐에 0번째 룸의 열쇠들을 다 넣는다.
- 큐의 첫번째 열쇠로 열 수 있는 방을 딴다.
- 그 방을 방문했던 적이 있다면 통과 없다면 또 그방 안에 있는 모든 열쇠를 큐안에 집어 넣는다.
코드
import Foundation
class Solution {
func canVisitAllRooms(_ rooms: [[Int]]) -> Bool {
let roomCount = rooms.count
var queue = rooms[0]
var visitedRoom = [Bool](repeating:false, count: roomCount)
visitedRoom[0] = true
while !queue.isEmpty {
let roomNumber = queue.removeFirst()
if visitedRoom[roomNumber] {
continue
} else {
visitedRoom[roomNumber] = true
queue += rooms[roomNumber]
}
}
if Set(visitedRoom).contains(false) {
return false
}
return true
}
}
반응형
'알고리즘' 카테고리의 다른 글
[Heap] 우선순위 큐 - LeetCode Swift (0) | 2021.08.11 |
---|---|
[Stack] daily-temperatures - LeetCode Swift (0) | 2021.08.09 |
[정렬] 줄 세우기 - 백준 2252번 Swift (0) | 2021.08.05 |
[Queue] 배열 구간 최솟값/최댓값 구하기 (0) | 2021.08.03 |
[그리디] 큰 수 만들기 - 프로그래머스 Swift (0) | 2021.08.02 |