feat: Add Ruby code - chapter "Backtracking" (#1373)

* [feat] add ruby code - chapter backtracking

* feat: add ruby code block - chapter backtracking
This commit is contained in:
khoaxuantu
2024-05-24 14:41:40 +07:00
committed by GitHub
parent 21be3fdaf8
commit aa818945f0
11 changed files with 503 additions and 0 deletions

View File

@ -406,7 +406,27 @@
=== "Ruby"
```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"