本身寫的一個算法,用node來代替存儲每一個可行點的歷史串。可是LC仍是過不了,由於超時: java
//To avoid memory issues, use new node for it private class WLNode { public String str; public WLNode parent; public WLNode(String str, WLNode parent){ this.str = str; this.parent = parent; } } private void findRlt(WLNode node, List<List<String>> rlt){ // print("find a solution "); List<String> item = new ArrayList<String>(); WLNode cur = node; while(cur != null){ item.add(0, cur.str); cur = cur.parent; } rlt.add(item); } public List<List<String>> findLadders(String beginWord, String endWord,Set<String> wordList) { //key is that each node needs a level List<List<String>> rlt = new ArrayList<List<String>>(); wordList.add(beginWord); wordList.add(endWord); //map to determine levels Map<String, Integer> levelMap = new HashMap<String, Integer>(); for(String temp : wordList){ levelMap.put(temp, 1); } Queue<WLNode> que = new LinkedList<WLNode>(); que.add(new WLNode(beginWord, null)); while(!que.isEmpty()){ WLNode node = que.remove(); String cur = node.str; int curLevel = levelMap.get(cur); // query for(int i = 0; i < cur.length(); i ++){ for(char x = 'a'; x <= 'z'; x ++){ if(cur.charAt(i) == x){ continue; } String next = cur.substring(0, i) + x + cur.substring(i + 1); if(wordList.contains(next)){ if(next.equals(endWord) && curLevel + 1 > levelMap.get(endWord) && levelMap.get(endWord) != 1){ // print("Found solution!!"); break; } if(levelMap.get(next) == 1 || curLevel + 1 <= levelMap.get(next)){ WLNode nodeToAdd = new WLNode(next, node); levelMap.put(next, curLevel + 1); que.add(nodeToAdd); if(next.equals(endWord)){ findRlt(nodeToAdd, rlt); } } } } } } return rlt; }
果真是應該先BFS而後DFS,這樣一來能夠不用index根本不會遇到的路徑,二來從後往前走能夠避免不須要的路。 node