美文网首页
剑指 Offer II 109. 开密码锁

剑指 Offer II 109. 开密码锁

作者: 邦_ | 来源:发表于2022-08-30 09:22 被阅读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
               
    }


相关文章

网友评论

      本文标题:剑指 Offer II 109. 开密码锁

      本文链接:https://www.haomeiwen.com/subject/fqqfgrtx.html