使用迭代广度优先搜索求解数独

发布于 2025-01-16 09:10:58 字数 285 浏览 6 评论 0原文

我有一项任务是使用迭代广度优先搜索算法来解决数独,但我正在努力将该算法准确地应用于这个问题。

我发现我需要一个队列,并且必须循环该队列直到它不为空。

我有以下算法来验证一个值是否在某个时刻适合特定单元格:

  1. 检查连续中不存在这样的值。
  2. 检查列中是否不存在此类值。
  3. 检查块中是否不存在此类值。

但是,当我在某个时候继续使用这种算法时,我必须回溯并更改之前选择的值,因为它可能是错误的。

如何使用 BFS 将回溯应用于此数独问题?

I have a task to solve sudoku using iterative Breadth first Search algorithm but I'm struggling with applying this algorithm exactly to this problem.

I figured out that I need a queue and I have to loop over this queue until it is not empty.

I have the following algorithm to validate a value whether it fits a particular cell at some moment:

  1. Check that no such values exist in a row.
  2. Check that no such values exist in a column.
  3. Check that no such values exist in a block.

But when I go on with such algorithm at some point I have to backtrack and change a previously selected value because it can turn out to be the wrong one.

How can I apply backtracking using BFS to this sudoku problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小伙你站住 2025-01-23 09:10:58

BFS 中不需要回溯。相反,BFS 为您提供了许多并行路径。如果一条路径最终导致不一致的网格,它就会消亡。唯一要做的就是对它不执行任何操作,即不要像通常那样将从它派生的下一个状态推送到队列上。

BFS 遍历本身可以通过多种方式进行组织,但它可能如下所示:

最初,队列从原始网格状态开始。然后,只要队列不为空并且仍然有空闲单元,就重复以下步骤:

  • 将网格状态从队列中出列。
  • 拿下一个空闲单元格。
  • 确定该空闲单元在不违反您列出的任何规则的情况下可以获得哪些值。
  • 为每一个创建一个网格状态,并将它们排入队列。

当第三个项目符号步骤产生没有可能的值时,分支将“死亡”。在这种情况下,下一步不会将任何内容放入队列,这正是您想要发生的情况。错误的道路就被消除了。该循环仍将继续并考虑队列中可能存在的其他替代网格。

There is no backtracking needed in BFS. Instead, BFS provides you with many paths in parallel. If one path turns out to lead to an inconsistent grid, it just dies. The only thing to do, is do nothing with it, i.e., don't push a next state derived from it on the queue, like you would normally do.

The BFS traversal itself can be organised in several ways, but here is what it could look like:

Initially the queue starts with the original grid state. Then repeat the following steps for as long as the queue is not empty and there are still free cells:

  • Dequeue a grid state from the queue.
  • Take the next free cell.
  • Determine which values this free cell can get without violating any of the rules you listed.
  • Create a grid state for each of these, and enqueue them.

A branch will "die" when the third bullet step produces no possible values. In that case the next step will not enqueue anything, which is just what you want to happen. The wrong path is eliminated. The loop will still continue and consider other, alternative grids which may be present on the queue.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文