[Swift] 불량 사용자

물복딱복준복
|2023. 6. 19. 03:31
import Foundation

func solution(_ userIds:[String], _ bannedIds:[String]) -> Int {
    
    var bannedIds = bannedIds
    var dict: [String: [String]] = [:]
    var regularExps = bannedIds.map { "^\($0.replacingOccurrences(of: "*", with: "[\\w]"))$" }
    var visited: [Bool] = Array(repeating: false, count: userIds.count)
    var userIdsDict: [String: Int] = [:]
    var result: Set<[String]> = []
    
    for (index, value) in userIds.enumerated() {
        userIdsDict[value] = index
    }
    
    for i in 0..<bannedIds.count {
        dict[bannedIds[i]] = userIds.filter { $0.range(of: regularExps[i], options: .regularExpression) != nil }
    }
    
    
    func dfs(_ answer: [String], _ visited: [Bool], _ bannedIds: [String]) {
        var visited = visited
        var bannedIds = bannedIds
        if bannedIds.isEmpty {
            result.insert(answer.sorted())
            return
        }
        let bannedId = bannedIds.removeFirst()
        
        for targetId in dict[bannedId]! {
            if visited[userIdsDict[targetId]!] {
                continue
            } else {
                visited[userIdsDict[targetId]!] = true
                dfs(answer + [targetId], visited, bannedIds)
                visited[userIdsDict[targetId]!] = false
            }
        }
        return
    }

    dfs([], visited, bannedIds)

    return result.count
}

 

'프로그래머스 > Lv.3' 카테고리의 다른 글

[Swift] 베스트앨범  (0) 2023.06.18
[Swift] 기지국 설치  (0) 2023.06.18
[Swift] 숫자 게임  (0) 2023.06.18
[Swift] 여행경로  (0) 2023.04.20
[Swift] 단어 변환  (0) 2023.04.18