[LeetCode]Word Ladder

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary

For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

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.

bfs    使用两个队列,一个存储当前状态,一个存储下一个状态,下一个状态由当前状态生成


public class Solution {
	int res = Integer.MAX_VALUE;
	Set<String> used =  new HashSet<>();
	public int ladderLength(String start, String end, Set<String> dict) {
		int level = 0;
		Queue<String> current = new LinkedList<>();
		Queue<String> next = new LinkedList<>();
		current.add(start);
		boolean found = false;
		while(!current.isEmpty()&&!found){
			level++;
			while(!current.isEmpty()&&!found){
				String str = current.poll();
			    Queue<String> extendStr = new LinkedList<>(extendString(str,dict));
				for(String s:extendStr){
					if(dict.contains(s)&&!used.contains(s)){
						next.offer(s);
						used.add(s);
					}
					if(end.equals(s)){
						found = true;
						break;
					}
				}
			}
			Queue<String> temp = current;
			current = next;
			next = temp;
		}
		if(found) return ++level;
		return 0;
	}

	private Queue<String> extendString(String current, Set<String> dict) {
		Queue<String> res = new LinkedList<>();
		char []str = current.toCharArray();
		for(int i=0;i<str.length;i++){
			char co = str[i];
			for(char ch ='a';ch<'z';ch++){
				str[i] = ch;
				String newStr = new String(str);
				res.add(newStr);
			}
			str[i] = co;
		}
		return res;
	}
}


你可能感兴趣的:(java,LeetCode,bfs)