127. Word Ladder#19
Conversation
| if letter == current_word[change_at]: | ||
| continue | ||
| new_word_candidates = current_word[:change_at] + letter + current_word[change_at+1:] | ||
| if new_word_candidates in wordList and new_word_candidates not in previous_sequence: |
There was a problem hiding this comment.
previous_sequence は1つの経路しか記録していないので、他の分岐が既に探索してきた経路と知らずに計算してしまいます。
There was a problem hiding this comment.
| - TTLでアクセプトしなかった | ||
| - 24 / 52 testcases passed | ||
| - どこがボトルネックなのだろう? | ||
| - 毎回deeepcopyしているところ? |
There was a problem hiding this comment.
previous_sequence のdeepcopy もそうですね。
あとは DFS で全ての経路を探索していることと、リストに対してin検索していることですかね。
There was a problem hiding this comment.
混乱してしまい、わからなくなってしまったためStep2に行く
深さ優先探索で全ての経路を探索していることがボトルネックですかね。
L: word の長さ
N: wordList の長さ
54行目の処理: O(L)
44行目の in 検索(list に対する探索: O(N)
この処理を、深さ優先探索によって候補となる word の経路数(最大で O((25L)^N) 程度)だけ繰り返しているため、全体として指数時間に近い計算量になっているようです。
There was a problem hiding this comment.
O((25L)^N) の部分ですが、例えば beginWord = "aa" の場合を考えると、
最初の候補として、
"ba", "ca", ..., "za"
のような word が生成されます。
次に "ba" を探索する際には、
"bb", "bc", ..., "bz"
のような候補を調べていきます。
今度は "ca" に対して同様の探索を行う……という流れで、順番に探索していく形になります。
aa
├─ ba
│ ├─ bb
│ ├─ bc
│ ├─ ...
│ └─ bz
├─ ca
│ ├─ cb
│ ├─ cc
│ ├─ ...
│ └─ cz
├─ da
│ └─ ...
└─ ...
There was a problem hiding this comment.
There was a problem hiding this comment.
この処理を、深さ優先探索によって候補となる word の経路数(最大で O((25L)^N) 程度)だけ繰り返しているため、全体として指数時間に近い計算量になっているようです。
コメントありがとうございます。すみません、↑についてまだ理解できていなく質問させてください🙇
25Lと、そのN乗はそれぞれ何を表していますでしょうか?
|
|
||
| """ | ||
| class Solution: | ||
| LOWER_ENGLISH_LETTERS = "abcdefghijklmnopqrstuvwxyz" |
There was a problem hiding this comment.
string.ascii_lowercase が使えそうです。
https://docs.python.org/ja/3.14/library/string.html#string.ascii_lowercase
この問題: Word Ladder
次の問題: Maximum Depth of Binary Tree