Word Ladder I

问题描述

Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, 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 {
    public int ladderLength(String beginWord, String endWord,
			Set<String> wordDict) {
		if (beginWord == null || endWord == null || wordDict == null) {
			return 0;
		}
		
		Queue<String> q = new LinkedList<String>();
		q.offer(beginWord);
		int level = 0;
		boolean flag = false;

		ps: while (true) {
			int size = q.size();
			for (int i = 0; i < size; i++) {
				String s = q.poll();
				for (int j = 0; j < s.length(); j++) {
					char[] cc = s.toCharArray();
					for (int k = 0; k < 26; k++) {
						char c = (char) ('a' + k);
						if (c == cc[j]) {
							continue;
						}
						cc[j] = c;
						String new_s = new String(cc);
						if (new_s.equals(endWord)) {
							flag = true;
							break ps;
						}
						if (wordDict.contains(new_s)) {
							q.offer(new_s);
							wordDict.remove(new_s);
						}
					}
				}
			}
			if (q.isEmpty()) {
				break;
			}
			++level;
		}

		return flag ? level + 2 : 0;
	}
}

 

posted @ 2015-08-17 20:27  Chapter  阅读(146)  评论(0编辑  收藏  举报