본문 바로가기

개발/알고리즘

[LeetCode] 841. 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

입력 & 출력

각 방에는 방에 들어갈 수 있는 키가 들어있다
모든 방에 출입할 수 있다면 true를 출력하라

풀이

처음부터 모든 방을 탐색하는 것이 아니다
첫번째 방을 시작으로 들어갈 수 있는 방이 주어진다
방을 방문했을 경우 해당 방에 다시 들어갈 필요는 없으니 이를 유의하며 탐색한다

 

Swift 전체 코드

var visit = Array(repeating: false, count: rooms.count)
visit[0] = true

func dps(start: Int, end: [Int]) {
    visit[start] = true
    for i in end {
        if visit[i] == false {
            dps(start: i, end: rooms[i])
        }
    }
}

dps(start: 0, end: rooms[0])

return visit.contains(false) ? false : true
반응형