From 3f53204a9fee441266a21db7f84db6c69583c270 Mon Sep 17 00:00:00 2001 From: Manuel Pineda Date: Sat, 9 Jan 2021 20:49:02 +0100 Subject: [PATCH] [LeetCode] Add daily challenge. --- solved/LeetCode/Challenges/2020/January/09.kt | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 solved/LeetCode/Challenges/2020/January/09.kt 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 + } +}