Skip to content

Commit

Permalink
[LeetCode] Add daily challenge.
Browse files Browse the repository at this point in the history
  • Loading branch information
pin3da authored Jan 9, 2021
1 parent 7964273 commit 3f53204
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions solved/LeetCode/Challenges/2020/January/09.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
class Solution {
fun ladderLength(beginWord: String, endWord: String, wordList: List<String>): Int {
if (endWord !in wordList) {
return 0
}
val valid = wordList.toSet()
val inf = 10000
val dist = mutableMapOf<String, Int>()
for (w in wordList) {
dist[w] = inf
}
dist[beginWord] = 1
val q = ArrayDeque<CharArray>()
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
}
}

0 comments on commit 3f53204

Please sign in to comment.