127. Word Ladder - BFS



這題是要找出 start 文字每次換一個字的狀況下, 這字有在 wordlist,
並且能從start string 換字走到 end string, 換最少的數目
idea:
無向圖中兩個頂點之間的最短路徑的長度,可以通過 BFS 遍歷得到
為什麼BFS得到的路徑最短?可以把起點和終點所在的路徑拉直來看,兩點之間線段最短;
已知目標頂點的情況下,可以分別從起點和目標頂點(終點)執行 BFS,直到遍歷的部分有交集,這是 BFS 的思想。
有沒有在 wordlist 內, 用 hashset 判斷 contains
此題可以用雙BFS, 目前先用單BFS
https://leetcode.com/problems/word-ladder/discuss/40704/Java-Solution-using-BFS-with-explanation
main idea:
time: O(26×wordLen), qsize is too small, ignore?
space: O(26×wordLen)

Set put wordList
Q.offer(begin)
BFS, step = 1
replace each char to test set, if set contains endWord, return step+1. else offer Q, remove newword from set
step++
end return 0
注意這段
如果charArray在最外面就取出來了, 因為 array不是immutable, 真的會被改掉!
下面這例子,第一個字母跑完後, 直接變最後的 z 了, 不是原本的值了

但如果每次都從頭從cur裡面轉出來, string cur 還是原本的樣子

像這樣的寫法, 最後還要做恢復


所以結論:
要在這裡再取出

終止條件移到 poll 之後
this is better, and as the same with leetcode 433
為什麼有些題解會需要 visited set? 我這個不需要?
因為我的作法在有對應時有對 wordset 做 remove newword, 所以不需要多一個 visited set 來檢查
newest version
key is here
and if we don't remove word from set, it will case inf loop,

when doing changes, ok, we geneare dog,
and add to queue, after this it generate hot...
hot generate dog again, and there is still dog in Set -> inf loop!!
Last updated
Was this helpful?