如何找出2D数组元素所在的子网格

时间:2015-03-25 17:18:19

标签: c++ arrays multidimensional-array

C ++初学者。我正在尝试制作一个数独求解程序,所以我必须检查它所在的9x9盒子中是否存在值。

这是我的代码,用于检查元素是否遵循规则:

//constants for rows and columns of the sudoku puzzle, can be changed
const int ROWS = 9;
const int COLS = 9;

bool follows_rule(int grid[ROWS][COLS], int rowIndex, int colIndex, int value){


    for (int i = 0; i < COLS; i++){ 
        if (grid[rowIndex][i] == value) //check if there are any other values on the same column
            return false;
        if (grid[i][colIndex] == value) //or the same row
            return false;
    }
    //to-do: check if another equal value exists in the 9x9 box
    return true;
}

//returns true if another element has the same value as "value", false otherwise
bool exists_in_2d_array(int grid[ROWS][COLS], int value){
    for (int x = 0; x < ROWS / 3; x++)
    {
        for (int y = 0; y < COLS / 3; y++)
        {
            if (grid[x][y] == value)
            {
                return true;
            }
        }
    }
    return false;
}

我的想法是找出当前元素的坐标导致哪个9x9框,然后将该9x9网格放在另一个2D数组中,并检查元素的值是否存在于网格中的其他位置。不过,我真的不知道怎么做。

1 个答案:

答案 0 :(得分:1)

SUDOKU规则要求数字仅使用一次:

  • 规则1:每一行
  • 规则2:每栏
  • 规则3:在9x9网格的每个3x3子网格中

如果允许值,函数follows_rule()将检查给定的网格位置。目前它仅检查规则1和2.我建议您使用以下规则3的代码:

bool follows_rule(int grid[ROWS][COLS], int rowIndex, int colIndex, int value){
    for (int i = 0; i < COLS; i++){
        if (grid[rowIndex][i] == value)
            return false;
        if (grid[i][colIndex] == value) // ATTENTION THIS IS OK BECAUSE ROWS==COOLS !!
            return false;
    }
    // Check if another equal value exists in the 3x3 box 
    int sgc = colIndex / 3;   // in wich subgrid are we ?
    int sgr = rowIndex / 3; 
    // check all the elements of the 3x3 grid startic at sgr, sgc
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            if (grid[sgr + i][sgc + j] == value)
                return false; 
    return true;
}

您可以使用以下代码测试3x3验证:

int sudoku[ROWS][COLS] = {
        { 1, 0, 0, 0, 0, 0, 0, 8, 0 },
        { 0, 0, 2, 0, 0, 0, 0, 0, 0 },
        { 0, 3, 0, 0, 0, 0, 0, 0, 0 },
        { 0, 0, 0, 1, 3, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 0, 5, 0, 0, 0 },
        { 0, 0, 0, 0, 8, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 0, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 0, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};

if (follows_rule(sudoku, 1, 0, 1) == false
    && follows_rule(sudoku, 1, 0, 4) == true
    && follows_rule(sudoku, 5, 5, 8) == false
    && follows_rule(sudoku, 5, 5, 1) == false
    && follows_rule(sudoku, 5, 5, 7) == true)
    cout << "Test ok !" << endl; 
else cout << "Tests failed" << endl;