127. 单词接龙

127. 单词接龙

https://leetcode-cn.com/problems/word-ladder/

func ladderLength(beginWord string, endWord string, wordList []string) int {
	i := 0
	n := len(wordList)
	if n == 0{
		return 0
	}
	for i=0;i<n;i++{
		if wordList[i] == endWord{
			break
		}
	}
	if i == n {
		return 0
	}
	//bfs
	flag := make([]bool,n)
	var queue []string
	queue = append(queue,beginWord)
    res := 0
	for len(queue) != 0 {
		size := len(queue)
        res++
		for i:=0;i<size;i++ {
			q := queue[0]
			queue = queue[1:]
			for j:=0;j<n;j++{
				if flag[j] == false && IsValid(q,wordList[j]) == true{
					flag[j] = true
					if wordList[j] == endWord{
						return res+1
					}
					queue = append(queue,wordList[j])
				}
			}
		}
	}
	return 0
}

//是否相差一个字母
func IsValid(str string,next string) bool{
	count := 0
	for i:=0;i<len(str);i++{
		if str[i] != next[i]{
			count++
		}
	}
	return count == 1
}

  

posted on 2020-04-21 20:56  wsw_seu  阅读(166)  评论(0编辑  收藏  举报

导航