leetcode解题之127. Word Ladder Java版 (单词等长变换)

127. Word Ladder

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence frombeginWord toendWord, such that:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list. Note thatbeginWord isnot a transformed word.

For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.

UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

无向图求最短路 - BFS 中的level order

给出两个单词(start和end)和一个字典,找到从start到end的最短转换序列

比如:

  1. 每次只能改变一个字母。
  2. 变换过程中的中间单词必须在字典中出现。
思路:这时一道bfs的题,开始突然反应不过来。 可以想象成一棵树,根节点是start字符串,第二层是所有的和它相差一个字母的字符串(之前出现过的,之后就没有必要出现了,因为出现的话,也是abc变成bbc又变回abs,没有意义),用一个hashmap来保存每一个节点的所处的层数,还需要一个队列来实现广度优先搜索,因为是从顶层到底层来遍历的,所以发现等于end的时候的层数值就是最小的,返回即可。

import java.util.*;
public class word {
	public int ladderLength(String beginWord, String endWord, List wordList) {
		if (beginWord == null || endWord == null || beginWord.length() == 0 || endWord.length() == 0
				|| beginWord.length() != endWord.length())
			return 0;
		// 此题关键是去重,还有去除和beginWord,相同的单词
		Set set = new HashSet(wordList);
		if (set.contains(beginWord))
			set.remove(beginWord);
		Queue wordQueue = new LinkedList();
		int level = 1; // the start string already count for 1
		int curnum = 1;// the candidate num on current level
		int nextnum = 0;// counter for next level
		// 或者使用map记录层数
		// Map map = new HashMap();
		// map.put(beginWord, 1);
		wordQueue.add(beginWord);

		while (!wordQueue.isEmpty()) {
			String word = wordQueue.poll();
			curnum--;
			// int curLevel = map.get(word);
			for (int i = 0; i < word.length(); i++) {
				char[] wordunit = word.toCharArray();
				for (char j = 'a'; j <= 'z'; j++) {
					wordunit[i] = j;
					String temp = new String(wordunit);

					if (set.contains(temp)) {
						if (temp.equals(endWord))
							// return curLevel + 1;
							return level + 1;
						// map.put(temp, curLevel + 1);
						nextnum++;
						wordQueue.add(temp);
						set.remove(temp);
					}
				}
			}
			if (curnum == 0) {
				curnum = nextnum;
				nextnum = 0;
				level++;
			}
		}
		return 0;
	}
}



你可能感兴趣的:(leetcode)