Shu*_*ham 0 language-agnostic algorithm matrix
好吧,我正在处理数独求解算法和生成,但坚持相当简单的任务.我已经检查过,一个数字是否真的适合行位和列方式.但它让我疯狂的是块检查,即数字是否真的适合3x3块.
它必须足够简单,但我无法真正达到解决方案.简而言之,我想知道矩阵中的位置所属的3x3块.以下是一些断言案例.块号,行号和列号没有索引从0开始.
assert("x( 0, 8 ) === 2");
assert("x( 8, 8 ) === 8");
assert("x( 3, 3 ) === 4");
assert("x( 3, 7 ) === 5");
assert("x( 7, 1 ) === 6");
Run Code Online (Sandbox Code Playgroud)
x( i , j )返回块号,其中i= row和j= col.
不只是:
block = 3 * (i / 3) + (j / 3)
Run Code Online (Sandbox Code Playgroud)
(假设整数运算).
我会编写一个支票,就像这样(在伪C++中)
// row = row to check
// col = column to check
// checkNum = number we are thinking of inserting
bool check(int row, int col, int checkNum)
{
int blockRow = 3 * (row/3);
int blockCol = 3 * (col/3);
for(int i = 0 ; i < 9 ; i++)
{
if(grid[row][i] == checkNum) return false; // number exists in the row.
if(grid[i][col] == checkNum) return false; // number exists in the col.
if(grid[blockRow + i/3][blockCol + i%3] == checkNum) return false; // number exists in the block.
}
return true;
}
Run Code Online (Sandbox Code Playgroud)