剑指 Offer II 109. 开密码锁

2022-08-30  本文已影响0人  邦_

和108很像



func openLock(_ deadends: [String], _ target: String) -> Int {

        
        var numSet = Set.init(deadends)
        if numSet.contains("0000"){
            return -1
        }
        var tempArray = [String]()
        tempArray.append("0000")
        var count = 0
        while tempArray.count > 0 {
            
            let len = tempArray.count
            for _ in 0..<len {
                
                let cur = tempArray.removeLast()
                if cur == target {
                    return count
                }
                let nextArr = getNextNums(cur)
                
                for num in nextArr{
                    if !numSet.contains(num){
                        tempArray.insert(num, at: 0)
                        numSet.insert(num)
                    }
                }
                
            }
            count += 1

        }
        
        
        
        return -1
      
    }
    
    func getNextNums(_ num:String) -> [String]{
        var nums = Array(num)
        var res = [String]()
        for i in 0..<4{
            let temp = nums[i]
            let tempNum = Int(String(temp))!
            let num1 = (tempNum + 1) % 10
            var num2 = tempNum
            if tempNum == 0 {
                 num2 = 9
            }else{
                num2 = tempNum - 1
            }
            nums[i] = Character(String(num1))
            res.append(String(nums))
            nums[i] = Character(String(num2))
            res.append(String(nums))
            //还原回去
            nums[i] = temp
        
        }
        return res
               
    }


上一篇下一篇

猜你喜欢

热点阅读