Repeated answer : sudoku(A, i, j)
has the side effect of writing data to A
When you call if(sudoku(A, i+1, j) && sudoku(A, i, j+1) && sudoku(A, i+1, j+1))
and you press the second sudoku(A, i, j+1)
check sudoku(A, i, j+1)
, this is not the same A
, and you do not check what you think. I fixed this by changing the two lines where your if
appears, and instead only one check is performed: sudoku(A, (i+1)%9, j+(i+1)/9)
Old answer : your code does not work because sudoku
does not behave the way you thought. You must roll back with the search depth of the first search. But you do not do this: if(sudoku(A, i+1, j) && sudoku(A, i, j+1) && sudoku(A, i+1, j+1))
is neither BFS nor DFS and this causes your algorithm to crash
Here is a slightly modified version where I replace the violating part of sudoku(A, (i+1)%9, j+(i+1)/9)
, and it works.
Edit: if(sudoku(A, i+1, j) && sudoku(A, i, j+1) && sudoku(A, i+1, j+1))
is a violator for the following reason:
sudoku(A, i, j)
true if the ANY rectangle from (i, j) to the lower right contains a valid fill. that is, you can enter numbers, and they do not violate sudoku rules. It is true that you want to compute sudoku(A,0,0)
- But I will give an example where it fails: suppose you calculate
if(sudoku(A,1,0) && sudoku(A,0,1) && sudoku(A,1,1))
. You start with sudoku(A, 1, 0)
and return true. Now you have the filling of almost all A (except the top row). You move on to sudoku(A,0,1)
calculations, but if the almost complete filling that you did earlier is actually invalid (there is no way to fill the top line), your algorithm will work immediately. - In other words, your code crashes because calling
sudoku(A, i, j)
has a side effect (writing data to A), and when you click the second third logical element in if
, you are not dealing with the correct A
Here is the code updated in your example
#include <iostream>
Exit
5 3 4 6 7 8 9 1 2 6 7 2 1 9 5 3 4 8 1 9 8 3 4 2 5 6 7 8 5 9 7 6 1 4 2 3 4 2 6 8 5 3 7 9 1 7 1 3 9 2 4 8 5 6 9 6 1 5 3 7 2 8 4 2 8 7 4 1 9 6 3 5 3 4 5 2 8 6 1 7 9