简体   繁体   中英

avoiding repeats in numbers for a 3x3 grid C++

I'm trying to make a solver that checks the block to make sure that no number repeats. Unfortunately, I can not get the correct logic on this and I'm not sure what I am doing incorrectly. Here is what I've got:

not quite sure why this is not working. Here's my code.

bool sudoku :: check_if_non_repeat(int r, int c, int v) //where r=row, c=column, v=value

Any idea why this is not working? I'm just getting infinite loops

if (!(j = brow && k == bcol)) 

检查j = ....应该是==

I'm not sure what you tried to do, but I would do it like this:

bool sudoku :: check_if_non_repeat(int r, int c, int v) //where r=row, c=column, v=value
{ 
    int brow = r/3;
    int bcol = c/3;
    for (int j = brow * 3; j < (brow * 3 + 3); j++)
        for (int k = bcol * 3; k < (bcol * 3 + 3); k++) 
            if (sudoku_array[j][k] == v) 
                    return true;
    return false;
}

EDIT: As noted below, the if statement need to be more complicated:

            if (   sudoku_array[j][k] == v
                && v != 0
                && !(j == r && k == c)) 
                    return true;

I'm about to tell you about a different approach to the problem. I made a full solver a long while ago, and it basically used the opposite approach.

For each field, I had a std::bitset<9> which told me which values were still possible in that field. Each insertion would then update the other fields in the same row, column and box to remove that possibility, recursively filling out subsequent fields when any one of the them had one option left.

If it then tried to fill a number which was no longer allowed, then the last input given was no longer a valid number for that spot. That was also a far more thorough check than you're doing here: you won't be checking if you close off the last possibility for another field in the same row/column/box, let alone others.

I never did a couple planned optimizations, but even without them it outperformed (too quick to notice) my friend's solver (>50 seconds). Mostly because he had code like yours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM