Dividing a 9x9 2d array into 9 sub-grids (like in sudoku)? (C++)

前提是你 提交于 2019-12-17 20:03:47

问题


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?


回答1:


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 |
+---+---+---+



回答2:


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, ...)




回答3:


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
    }
}


来源:https://stackoverflow.com/questions/4718213/dividing-a-9x9-2d-array-into-9-sub-grids-like-in-sudoku-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!