高级农民
- 积分
- 1733
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2011-3-19
- 最后登录
- 1970-1-1
|
贴一个我的,感觉比较方便记忆和简洁,易读性好:
避免了adjacent list,也避免了前驱节点。
用的有两点:
1 先走一遍bfs,用一个HashMap记录dict里的每一个词到start的距离
2 再来一遍dfs,找到所有的解
注意dfs时,要把start和end的位置颠倒一下,因为oj的数据是前密后疏的- public static List<List<String>> findLadders(String start, String end, Set<String> dict) {
- List<List<String>> ret = new ArrayList<>();
- List<String> seq = new ArrayList<>();
- HashMap<String,Integer> path = new HashMap<>();
- bfs(start, end, dict, path);
- dfs(ret, seq, end, start, dict, path);
- for(List<String> l : ret) l.add(end);
- return ret;
- }
- private static void bfs(String start, String end, Set<String> dict, HashMap<String,Integer> path) {
- Queue<String> queue = new LinkedList<>();
- queue.add(start);
- path.put(start, 0);
- while(!queue.isEmpty()) {
- String cur = queue.remove();
- for(int i=0; i<start.length(); i++) {
- char[] cc = cur.toCharArray();
- for(char c='a'; c<='z'; c++) {
- if(c == cur.charAt(i)) continue;
- cc[i] = c;
- String next = new String(cc);
- if(dict.contains(next) || next.equals(end)) {
- if(!path.containsKey(next)) {
- path.put(next, path.get(cur)+1);
- queue.add(next);
- }
- }
- }
- }
- }
- }
- private static void dfs(List<List<String>> ret, List<String> seq, String start, String end,
- Set<String> dict, HashMap<String,Integer> path) {
- if(start.equals(end)) {
- List<String> newSeq = new ArrayList<>(seq);
- Collections.reverse(newSeq);
- ret.add(newSeq);
- return;
- }
- if(!path.containsKey(start)) return;
- for(int i=0; i<start.length(); i++) {
- char[] cc = start.toCharArray();
- for(char c='a'; c<='z'; c++) {
- if(c == start.charAt(i)) continue;
- cc[i] = c;
- String next = new String(cc);
- if(dict.contains(next) && path.get(next) == path.get(start)-1 || next.equals(end)) {
- seq.add(next);
- dfs(ret, seq, next, end, dict, path);
- seq.remove(next);
- }
- }
- }
- }
复制代码 |
|