본문 바로가기

알고리즘

[DFS] keys and rooms - LeetCode Swift

문제 : 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

 

풀이방법

  1. 큐에 0번째 룸의 열쇠들을 다 넣는다.
  2. 큐의 첫번째 열쇠로 열 수 있는 방을 딴다.
  3. 그 방을 방문했던 적이 있다면 통과 없다면 또 그방 안에 있는 모든 열쇠를 큐안에 집어 넣는다.

 

코드

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
    }
}
반응형