What is wrong with my sudoku solver function?

ok, so I changed my function to a backtracking function (which I found on the Internet). It still reads from the file and enters it into an array, the validation function works correctly, so I did not change this. If you are wondering the following: the puzzle I'm trying to solve (where zeros are empty space).

0 5 0 0 2 0 0 7 0 7 2 0 4 0 3 0 0 0 9 0 0 0 5 0 6 2 0 0 0 5 0 8 6 0 0 0 1 0 0 0 4 0 0 0 8 0 0 0 2 3 0 4 0 0 0 9 3 0 1 0 0 0 2 0 0 0 3 0 2 0 4 6 0 8 0 0 0 0 0 1 0 // backtracking function void Sudoku::solvePuzzle() { int x = 0; int y = 0; int r = 0; bool back_flag; while (r < 81) { back_flag = true; x = r/9; y = r%9; for(int num = arr[x][y]; num < 10 && back_flag; num++) { if(check(x,y,num)) { arr[x][y] = num; back_flag=false; break; } else if(num >= 9) { arr[x][y] = 0; } } if(back_flag) { r--; } else { r++; } } } 
+4
source share
1 answer

I do not know if these are the only errors, but at first glance I think instead

  if (count == 1 && arr[r][c] == 0) { tempNum = num; } else { tempNum = 0; } count++; 

he should be

  count++; if (count == 1) { tempNum = num; } 

and instead

  if (count == 1 && check(r, c, num) && arr[r][c] == 0) { arr[r][c] = tempNum; 

he should be

  if (count == 1 && check(r, c, tempNum)) { arr[r][c] = tempNum; 

or simply

  if (count == 1 ) { arr[r][c] = tempNum; 

because when count==1 , then check(r, c, tempNum) cannot be false if your check function has no side effects.

By the way, the code becomes much better readable if you arrange it as follows:

 for (int r = 0; r < MAX_ROW; r++) { for (int c = 0; c < MAX_COL; c++) { if(arr[r][c] != 0) continue; // ** no tests for arr[r][c] == 0 in this code block any more // ... } } 

And the last: you have to stop the algorithm, if the number of zeros in the outer loop no longer changes from one iteration to another, there will be SuDoKus, which your solver cannot solve, and you do not want to force you to program in an infinite loop for these, I think.

+1
source

Source: https://habr.com/ru/post/1381852/


All Articles