This link has a Backtracking implementation of the Sudoku Solver algorithm. Notice how line number 42, reverts the value initially assigned to a cell, to another value, in case the initially assigned value did not give a valid output.
However, I don't understand how merely changing the value of that cell alone is sufficient. This call could've triggered many other calls, and since arrays (matrices) are passed by memory (reference), it does not keep a copy of the matrix (grid[N][N]) at every invocation of the recursive function, and so changes till the base case of the recursion will reflect even in the first frame of recursion by the time it returns back.
According to me, just before calling the recursive function, you should make a temporary copy of grid[N][N] and restore it as soon as the call gets returned, and before the next function in the same frame is called.
Something like
for (int num = 1; num <= N; num++)
{
// if looks promising
if (isSafe(grid, row, col, num))
{
//save grid state
int[][] temp = new int[N][N];
save(temp,grid); //copy all values from grid to temp
// make tentative assignment
grid[row][col] = num;
// return, if success, yay!
if (SolveSudoku(grid))
return true;
//restore grid state
restore(temp,grid); //copy all values from temp back to grid
// failure, unmake & try again
grid[row][col] = UNASSIGNED;
}
}
Please help me understand this detail.