Swift Implementation, BFS


  • 0
    I
    func ladderLength(beginWord:String,endWord:String, inout wordList:Set<String>) -> Int
    {
        var queue = Queue<String>()
        queue.enqueue(beginWord)
        wordList.insert(endWord)
        wordList.remove(beginWord)
        var level = 1
        while queue.peek() != nil{
            let size = queue.size
            for _ in 0 ..< size {
                let str = queue.deque()
                if(str == endWord){return level}
                for string in neighbours(str, wordList: &wordList)
                {
                    queue.enqueue(string)
                }
            }
            level += 1
            
        }
        
        return level
    }
    
    func neighbours(word:String,inout wordList:Set<String>) ->[String]
    {
        var result = [String]()
        let alpahabetArray = Array("abcdefghijklmnopqrstuvwxyz".characters)
        for i in 0 ..< word.characters.count
        {
            var chars = Array(word.characters)
            for j in 0 ..< alpahabetArray.count {
                chars[i] = alpahabetArray[j]
                let newWord = String(chars)
                if(wordList.contains(newWord))
                {
                    result.append(newWord)
                    wordList.remove(newWord)
                }
            }
        }
        return result
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.