kt: add «773. Sliding Puzzle»

URL:	https://leetcode.com/problems/sliding-puzzle/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-11-26 00:02:35 +01:00
parent 6e55e96ef0
commit 7dee18a1ca
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

63
kt/sliding-puzzle.kt Normal file
View file

@ -0,0 +1,63 @@
class Solution {
companion object {
private val DIRECTIONS: List<List<Int>> =
listOf(
listOf(1, 3),
listOf(0, 2, 4),
listOf(1, 5),
listOf(0, 4),
listOf(1, 3, 5),
listOf(2, 4),
)
private val TARGET: String = "123450"
private fun swap(
board: String,
i: Int,
j: Int,
): String {
val cells = board.toMutableList()
val tmp = cells[i]
cells[i] = cells[j]
cells[j] = tmp
return cells.joinToString(separator = "")
}
}
fun slidingPuzzle(board: Array<IntArray>): Int {
val startState =
board.flatMap { it.asSequence() }.joinToString(separator = "") {
it.toString()
}
val seen = mutableSetOf<String>(startState)
val queue = ArrayDeque<String>(listOf(startState))
var moves = 0
while (queue.isNotEmpty()) {
for (i in 1..queue.size) {
val current = queue.removeFirst()
if (current == TARGET) {
return moves
}
val zeroIdx = current.indexOf('0')
DIRECTIONS[zeroIdx].forEach {
val next = swap(current, zeroIdx, it)
if (seen.contains(next)) {
return@forEach
}
seen.add(next)
queue.addLast(next)
}
}
moves += 1
}
return -1
}
}