Word Ladder——LeetCode

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.

 

题目大意:给定两个等长的单词,各一个字典,每次只能变换一个字符得到中间词,此中间词必须在字典里存在,求从一个单词变换到另一个单词最短需要多少步。

解题思路:说实话这题一开始觉得不知道从哪儿下手,后来看了下tag是BFS,才有了思路,从字典里寻找与起始单词距离为1的所有单词,加入bfs队列,然后当队列非空,取出队列中的单词,查找在字典里的所有与之距离为1的单词,直到找到结束单词或者全部遍历完没有合法解,返回0;

Talk is cheap>>

    public int ladderLength(String start, String end, Set<String> dict) {
        if (transInOne(start, end)) {
            return 2;
        }
        Queue<String> queue = new ArrayDeque<>();
        queue.add(start);
        int length = 1;
        while (!queue.isEmpty()) {
            length++;
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                String toSearch = queue.poll();
                if (transInOne(toSearch, end)) {
                    return length;
                }
                for (Iterator<String> iterator = dict.iterator(); iterator.hasNext(); ) {
                    String next = iterator.next();
                    if (transInOne(toSearch, next)) {
                        queue.offer(next);
                        iterator.remove();
                    }
                }
            }
        }
        return 0;
    }

    private boolean transInOne(String start, String end) {
        int i = 0;
        int res = 0;
        while (i < start.length()) {
            if (start.charAt(i) != end.charAt(i)) {
                res++;
                if (res > 1)
                    return false;
            }
            i++;
        }
        return true;
    }

 

posted @ 2015-04-06 19:49  丶Blank  阅读(214)  评论(0编辑  收藏  举报