feat: add ruby code block - chapter backtracking
This commit is contained in:
parent
906824ce11
commit
231e853219
@ -406,7 +406,27 @@
|
|||||||
=== "Ruby"
|
=== "Ruby"
|
||||||
|
|
||||||
```ruby title=""
|
```ruby title=""
|
||||||
|
### 回溯算法框架 ###
|
||||||
|
def backtrack(state, choices, res)
|
||||||
|
# 判断是否为解
|
||||||
|
if is_solution?(state)
|
||||||
|
# 记录解
|
||||||
|
record_solution(state, res)
|
||||||
|
return
|
||||||
|
end
|
||||||
|
|
||||||
|
# 遍历所有选择
|
||||||
|
for choice in choices
|
||||||
|
# 剪枝:判断选择是否合法
|
||||||
|
if is_valid?(state, choice)
|
||||||
|
# 尝试:做出选择,更新状态
|
||||||
|
make_choice(state, choice)
|
||||||
|
backtrack(state, choices, res)
|
||||||
|
# 回退:撤销选择,恢复到之前的状态
|
||||||
|
undo_choice(state, choice)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
```
|
```
|
||||||
|
|
||||||
=== "Zig"
|
=== "Zig"
|
||||||
|
Loading…
Reference in New Issue
Block a user