leetcode_wordladder,leetcode
題目描述
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, 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”]
As one shortest transformation is “hit” -“hot” -“dot” -“dog” -“cog”,
return its length 5.
解題分析
此題總體思路是廣度優先BFS搜尋,利用隊列可進行,但是幾次嘗試都逾時:
- 首先我利用關係矩陣表示圖關係,這樣TLE,分析也可看到N*N的複雜度。
- 後來利用鄰接表方式表示,注意到這裡小寫字母只有26個,又題目說明字串長度相同,則邊的數目最大L*26,鄰接表遍曆搜尋就很快N*L*26,但是建立鄰接表的過程還是N*N,依然TLE,嘗試發現對於大資料鄰接表建立的過程中就逾時了。
- 最後依然是利用邊數目有限的思想,由一個單詞直接去產生可達單詞然後判斷是否在字典中,這樣就不需要產生鄰接表了,這裡我由於最初資料處理使用了Linkedlist,使得在判斷是否屬於候選集的時候也就是contain object的時候費時,TLE,最後使用set結構,終於ac。
- 回顧很多知識點,BFS和隊列,矩陣和鄰接表,java的 set 和 collection, java的queue介面一般由linkedlist實現
詳細代碼
public class Solution {public int ladderLength(String beginWord, String endWord, Set<String> wordDict) { wordDict.add(endWord); wordDict.add(endWord); Queue<NodeString> queue = new LinkedList<NodeString>(); queue.add(new NodeString(beginWord, 1)); wordDict.remove(beginWord); while(!queue.isEmpty()) { NodeString current = queue.poll(); if(current.string.equals(endWord)) { return current.deep; } else { String tmp = current.string;//取點 找臨街的表,這裡藉助最大固定數目的變數來計算而非常規利用矩陣 for(int i=0;i<tmp.length();i++) { for(char c='a';c<='z';c++) { if(c==tmp.charAt(i)) { continue; } else { char cc[] = tmp.toCharArray(); cc[i] = c; String s = new String(cc); if(wordDict.contains(s)) { queue.add(new NodeString(s, current.deep+1)); wordDict.remove(s); } } } } } } return 0; } class NodeString { String string; int deep; public NodeString(String string , int deep) { this.string = string; this.deep = deep; } }}