diff --git a/solved/LeetCode/Challenges/2020/January/09.kt b/solved/LeetCode/Challenges/2020/January/09.kt new file mode 100644 index 00000000..cb0525fc --- /dev/null +++ b/solved/LeetCode/Challenges/2020/January/09.kt @@ -0,0 +1,37 @@ +class Solution { + fun ladderLength(beginWord: String, endWord: String, wordList: List): Int { + if (endWord !in wordList) { + return 0 + } + val valid = wordList.toSet() + val inf = 10000 + val dist = mutableMapOf() + for (w in wordList) { + dist[w] = inf + } + dist[beginWord] = 1 + val q = ArrayDeque() + q.add(beginWord.toCharArray()) + val target = endWord.toCharArray() + while (q.isNotEmpty()) { + val cur = q.removeFirst() + val st = String(cur) + val newDist = dist[st]!! + 1 + for (i in cur.indices) { + val next = cur.copyOf() + for (c in 'a'..'z') { + next[i] = c + if (next contentEquals target) { + return newDist + } + val stNext = String(next) + if (stNext in valid && newDist < dist.getOrDefault(stNext, inf)) { + dist[stNext] = newDist + q.add(next.copyOf()) + } + } + } + } + return 0 + } +}