我是牛爱网第二菜 level
获赞
945
粉丝
72
关注
35
看过 TA
69
门头沟学院
2020
Java
IP属地:上海
暂未填写个人简介
私信
关注
2019-06-08 15:37
门头沟学院 Java
那个长样例……怎么过去,不得不服这个样例设计者;有没有大佬用dfs过去的
好好复习:public class Solution { public List<List<String>> findLadders(String start, String end, List<String> words) { /** 核心思路是倒序拍 end--> list of word can to end to end word --> list of word to this word ... to begin */ Set<String> dict = new HashSet<>(words); List<List<String>> res = new ArrayList<List<String>>(); if(start.compareTo(end) == 0) return res; Set<String> visited = new HashSet<String>(); Set<String> cur = new HashSet<String>(); HashMap<String, ArrayList<String>> graph = new HashMap<String, ArrayList<String>>(); graph.put(end,new ArrayList<String>()); cur.add(start); boolean found = false; while (!cur.isEmpty() && found == false) { Set<String> queue = new HashSet<String>(); //next level queue for(String word : cur) { visited.add(word); } for(String str : cur) { char[] word = str.toCharArray(); for (int j = 0; j < word.length; ++j) { char before = word[j]; for (char ch = 'a'; ch <= 'z'; ++ch) { if (ch == before) continue; word[j] = ch; String temp = new String(word); if (!dict.contains(temp)) continue; if (found == true && end.compareTo(temp) != 0) continue; //not the shortest path if (end.compareTo(temp) == 0) { found = true; (graph.get(end)).add(str); continue; } if (!visited.contains(temp)) { queue.add(temp); if (!graph.containsKey(temp)) { ArrayList<String> l = new ArrayList<String>(); l.add(str); graph.put(temp,l); } else { (graph.get(temp)).add(str); } } } word[j] = before; } } cur = queue; } if (found == true) { ArrayList<String> path = new ArrayList<String>(); trace(res, graph, path, start, end); } return res; } public void trace(List<List<String>> res, HashMap<String, ArrayList<String>> graph, ArrayList<String> path, String start, String now) { path.add(now); if (now.compareTo(start) == 0) { ArrayList<String> ans = new ArrayList<String>(path); Collections.reverse(ans); res.add(ans); path.remove(path.size() - 1); return; } ArrayList<String> cur = graph.get(now); for (int i = 0; i < cur.size(); ++i) { trace(res,graph,path,start,cur.get(i)); } path.remove(path.size()-1); } }
0 点赞 评论 收藏
分享

创作者周榜

更多
关注他的用户也关注了:
牛客网
牛客企业服务