This commit is contained in:
krahets
2023-10-03 03:49:55 +08:00
parent 256ce30a95
commit 49ad0a6422
12 changed files with 166 additions and 16 deletions

View File

@@ -1020,7 +1020,27 @@ comments: true
=== "Rust"
```rust title=""
/* 回溯算法框架 */
fn backtrack(state: &mut State, choices: &Vec<Choice>, res: &mut Vec<State>) {
// 判断是否为解
if is_solution(state) {
// 记录解
record_solution(state, res);
// 停止继续搜索
return;
}
// 遍历所有选择
for choice in choices {
// 剪枝:判断选择是否合法
if is_valid(state, choice) {
// 尝试:做出选择,更新状态
make_choice(state, choice);
backtrack(state, choices, res);
// 回退:撤销选择,恢复到之前的状态
undo_choice(state, choice);
}
}
}
```
=== "C"