将 9x9 二维数组划分为 9 个子网格(就像数独一样)? (C++)

发布于 2024-10-12 08:22:34 字数 255 浏览 9 评论 0原文

我正在尝试编写一个数独解算器,我尝试这样做的方法是拥有一个 9x9 的指针网格,用于保存拥有解或有效可能值的“集合”对象的地址。

我能够使用 2 个 for 循环遍历数组,首先遍历每一列,然后转到下一行并重复。

然而,我很难想象如何指定特定单元属于哪个子网格(或框、块等)。我最初的印象是在 for 循环中包含 if 语句,例如 if row <; 2(行从 0 开始)&山口< 2 那么我们就在第一个街区,但这似乎变得很混乱。有更好的方法吗?

I'm trying to code a sudoku solver, and the way I attempted to do so was to have a 9x9 grid of pointers that hold the address of "set" objects that posses either the solution or valid possible values.

I was able to go through the array with 2 for loops, through each column first and then going to the next row and repeating.

However, I'm having a hard time imagining how I would designate which sub-grid (or box, block etc) a specific cell belongs to. My initial impression was to have if statements in the for loops, such as if row < 2 (rows start at 0) & col < 2 then we're in the 1st block, but that seems to get messy. Would there be a better way of doing this?

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

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

发布评论

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

评论(3

我也只是我 2024-10-19 08:22:34

您可以像这样从行和列计算块编号:

int block = (row/3)*3 + (col/3);

这对块进行编号,如下所示:

+---+---+---+
| 0 | 1 | 2 |
+---+---+---+
| 3 | 4 | 5 |
+---+---+---+
| 6 | 7 | 8 |
+---+---+---+

You could calculate a block number from row and column like this:

int block = (row/3)*3 + (col/3);

This numbers the blocks like this:

+---+---+---+
| 0 | 1 | 2 |
+---+---+---+
| 3 | 4 | 5 |
+---+---+---+
| 6 | 7 | 8 |
+---+---+---+
蒗幽 2024-10-19 08:22:34

我将创建一个包含 81 个条目的查找表。每个条目引用 9x9 网格中的一个单元格,并为您提供所需的信息(哪个框、哪列、哪行……)

I would create a lookup table with 81 entrys. Each entry refers to a cell in the 9x9 grid and gives you the information you need (which box, which column, which row, ...)

静谧 2024-10-19 08:22:34

我自己使用这个(但在 python 中,假设 x 和 y 从 0 到 9 互斥):

int bx, by;
for (bx = (x/3)*3; bx < (x/3)*3 + 3; bx++) {
    for (by = (y/3)*3; by < (y/3)*3 + 3; by++) {
        // bx and by will now loop over each number in the block which also contains x, y
    }
}

I use this myself (but then in python, assuming x and y go from 0 to 9 exclusive):

int bx, by;
for (bx = (x/3)*3; bx < (x/3)*3 + 3; bx++) {
    for (by = (y/3)*3; by < (y/3)*3 + 3; by++) {
        // bx and by will now loop over each number in the block which also contains x, y
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文