题目大意:

给一个开始单词beginword和一个结束单词endword, 再给一个单词列表wordList。从beginword变换到endword, 每次只能变换一个字母,且变换成的词属于wordList。

解决思路:

其实是个变相的BFS,寻找当前集合中相邻的可以进行变换的单词,更新当前集合,直到集合中出现endword。

另,一开始用DFS,递归解法,结果TLE。

超时解法:

var isExist  =  false
var minLen   = 0
var target   = ""
func ladderLength(beginWord string, endWord string, wordList []string) int {
    minLen = len(wordList)
    target = endWord
    bfs(1, beginWord, wordList)
    if isExist == false {
        minLen = 0
    }

    return  minLen
}

func bfs(curLen int, curStr string, remainList []string) {
    for i, remainStr := range remainList {
        diffNum := 0
        for j, curCh := range curStr {
            if byte(curCh) != byte(remainStr[j]) {
                diffNum++
            }

            if diffNum > 1 {
                break
            }
        }

        if target == curStr {
            isExist = true
            if minLen > curLen {
                minLen = curLen
                return
            }
        }

        if diffNum == 1 {
            bfs(curLen + 1, remainStr, append(remainList[:i], remainList[i+1:]...))
        }
    }
}
View Code

BFS:

func ladderLength(beginWord string, endWord string, wordList []string) int {
    
    var candiList = []string{beginWord}
    var minLen    = 1
    for len(candiList) > 0 {
        var tempList []string
        for _, candWord := range candiList {
            if candWord == endWord {
                return minLen
            }

            for i, word := range wordList {
                if word == candWord {
                    wordList = append(wordList[:i], wordList[i+1:]...)
                    break
                }
            }

            for _, word := range wordList {
                diffNum := 0
                for j, ch := range candWord {
                    if byte(ch) != byte(word[j]) {
                        diffNum++
                    }
                    if diffNum > 1 {
                        break
                    }
                }
                if diffNum == 1 {
                    tempList = append(tempList, word)
                }
            }

        }
        candiList = tempList
        minLen++
    }

    return  0
}

 

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/AndrewGhost/p/11878335.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!