From 231e853219bcc7cb54c6a3737c4f0d9e5d3c76e6 Mon Sep 17 00:00:00 2001 From: khoaxuantu <68913255+khoaxuantu@users.noreply.github.com> Date: Wed, 22 May 2024 10:29:54 +0700 Subject: [PATCH] feat: add ruby code block - chapter backtracking --- .../backtracking_algorithm.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/docs/chapter_backtracking/backtracking_algorithm.md b/docs/chapter_backtracking/backtracking_algorithm.md index 874f8d64c..dcdebd677 100644 --- a/docs/chapter_backtracking/backtracking_algorithm.md +++ b/docs/chapter_backtracking/backtracking_algorithm.md @@ -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"