leetcode 87: Word Ladder II
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) fromstart to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
Return
[ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
Note:
- All words have the same length.
- All words contain only lowercase alphabetic characters.
public class Solution { public ArrayList<ArrayList<String>> findLadders(String start, String end, HashSet<String> dict) { // Start typing your Java solution below // DO NOT write main() function ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
Queue<Node> queue = new LinkedList<Node>(); queue.offer(new Node(start, null)); HashSet<String> unique = new HashSet<String>(); boolean first = false; int min = Integer.MIN_VALUE;
while (!queue.isEmpty()) { Node n = queue.poll(); String s = n.c;
Sign: for (int i = 0; i < s.length(); i++) { for (char c = 'a'; c <= 'z'; c++) { StringBuilder sb = new StringBuilder(s); sb.setCharAt(i, c); String t = sb.toString(); if (t.equals(end)) { ArrayList<String> match = new ArrayList<String>(); match.add(end); while (n != null) { match.add(0, n.c); n = n.p; } if(!first){ first = true; min = match.size(); } else{ if(match.size()>min) return res; } res.add(match); }
if (!unique.contains(t) && dict.contains(t)) { queue.offer(new Node(t, n)); unique.add(s); } } } }
return res; }
static class Node {
public String c; public Node p;
public Node(String c, Node p) { this.c = c; this.p = p; } } }