[LeetCode] Word Ladder

来源:互联网 发布:北京java培训费用 编辑:程序博客网 时间:2024/05/24 05:43

Word Ladder


Given two words (start and end), and a dictionary, find the length of shortest transformation sequence fromstart 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.

LeetCode: https://oj.leetcode.com/problems/word-ladder/

这道题的求解思路为:对于start,首先找出dict中和start只有一个字符不同的字符串集合S1,对于该S1中的字符串,start到他们的最短距离为1;然后再求解dict中和S1中字符串只相差一个字符并且没有出现在S1中的字符集合S2;则start到S2中的字符的最短距离为2,通过上述过程计算循环计算下去,直到某个集合Si中出现end,则找到start到end的最短距离。

其实敏感的同学可以发现者其实是一颗以start为根的树,树中的节点包括start、end、dict中的字符串(如果包含end,则end一定为叶节点,但有可能出现在多个位置上);本题的目标其实是要找到从start到end的最短路径;对于这类问题,一般都采用DFS或BFS,由于树本身并没有事先建立好,所以不太适合采用DFS;而通过上面求解思路可知,采用BFS比较恰当。

代码如下:

public class Solution {    public int ladderLength(String start, String end, Set<String> dict) {        if(start == null || end == null || start.length() == 0 || end.length() == 0 || start.length() != end.length())            return 0;        Queue<String> queue = new LinkedList<String>();        HashSet<String> visited = new HashSet<String>();        queue.offer(start);        int depth = 1;        int cur = 1;        int next = 0;        while(!queue.isEmpty()){            String e = queue.poll();            cur--;            for(int i = 0; i < e.length(); i++){                char[] ca = e.toCharArray();                for(char c = 'a'; c <= 'z'; c++){                    ca[i] = c;                    String s = new String(ca);                    if(s.equals(end))                        return depth+1;                    if(dict.contains(s) && !visited.contains(s)){                        queue.offer(s);                        visited.add(s);                        next++;                    }                }            }            if(cur == 0){                cur = next;                next = 0;                depth++;            }        }        return 0;    }}

0 0
原创粉丝点击