hello-algo/codes/kotlin/chapter_backtracking/preorder_traversal_iii_template.kt
curtishd 306dc019ef
Add Kotlin code for computational complexity (#1090)
* feat(kotlin):new kotlin support files

* fix(kotlin):

    reviewed the formatting, comments and so on.

* fix(kotlin): fix the indentation and format

* feat(kotlin): Add kotlin code for the backtraking chapter.

* fix(kotlin): fix incorrect output of preorder_traversal_iii_template.kt file

* fix(kotlin): simplify kotlin codes

* fix(kotlin): modify n_queens.kt for consistency.

* feat(kotlin): add kotlin code for computational complexity.

* fix(kotlin): remove iteration folder.

* fix(kotlin): remove n_queens.kt file out of folder.

* fix(kotlin): remove some folders.

* style(kotlin): modified two chapters.
2024-02-27 17:04:57 +08:00

83 lines
No EOL
2.2 KiB
Kotlin

/**
* File: preorder_traversal_iii_template.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package chapter_backtracking.preorder_traversal_iii_template
import utils.TreeNode
import utils.printTree
import java.util.*
/* 判断当前状态是否为解 */
fun isSolution(state: List<TreeNode?>): Boolean {
return state.isNotEmpty() && state[state.size - 1]?.value == 7
}
/* 记录解 */
fun recordSolution(state: MutableList<TreeNode?>?, res: MutableList<List<TreeNode?>?>) {
res.add(state?.let { ArrayList(it) })
}
/* 判断在当前状态下,该选择是否合法 */
fun isValid(state: List<TreeNode?>?, choice: TreeNode?): Boolean {
return choice != null && choice.value != 3
}
/* 更新状态 */
fun makeChoice(state: MutableList<TreeNode?>, choice: TreeNode?) {
state.add(choice)
}
/* 恢复状态 */
fun undoChoice(state: MutableList<TreeNode?>, choice: TreeNode?) {
state.removeLast()
}
/* 回溯算法:例题三 */
fun backtrack(
state: MutableList<TreeNode?>,
choices: List<TreeNode?>,
res: MutableList<List<TreeNode?>?>
) {
// 检查是否为解
if (isSolution(state)) {
// 记录解
recordSolution(state, res)
}
// 遍历所有选择
for (choice in choices) {
// 剪枝:检查选择是否合法
if (isValid(state, choice)) {
// 尝试:做出选择,更新状态
makeChoice(state, choice)
// 进行下一轮选择
backtrack(state, listOf(choice!!.left, choice.right), res)
// 回退:撤销选择,恢复到之前的状态
undoChoice(state, choice)
}
}
}
/* Driver Code */
fun main() {
val root = TreeNode.listToTree(mutableListOf(1, 7, 3, 4, 5, 6, 7))
println("\n初始化二叉树")
printTree(root)
// 回溯算法
val res: MutableList<List<TreeNode?>?> = ArrayList()
backtrack(ArrayList(), mutableListOf(root), res)
println("\n输出所有根节点到节点 7 的路径,要求路径中不包含值为 3 的节点")
for (path in res) {
val vals = ArrayList<Int>()
for (node in path!!) {
if (node != null) {
vals.add(node.value)
}
}
println(vals)
}
}