Determine whether a Sudoku has a unique solution

后端 未结 2 787
北海茫月
北海茫月 2021-01-25 11:14

I\'m struggling with a backtracking algorithm to determine wether a Sudoku has a unique solution or if it has multiple Solutions. Here\'s the backtracking code i use:

         


        
相关标签:
2条回答
  • 2021-01-25 11:49

    The reset must be inside the for loop and after the if solve condition

     for (int val = 1; val <= 9; ++val) {
            if (legal(i,j,val,cells)) {
                cells[i][j] = val;
                if (solve(i+1,j,cells))
                    return true;
                cells[i][j] = 0; // reset on backtrack
            }
        }
    
    0 讨论(0)
  • 2021-01-25 12:01

    If you return a number instead of a boolean, you can distinguish between cases where there are 0, 1, or more than 1 solution(s).

    // returns 0, 1 or more than 1 depending on whether 0, 1 or more than 1 solutions are found
    static byte solve(int i, int j, int[][] cells, byte count /*initailly called with 0*/) {
        if (i == 9) {
            i = 0;
            if (++j == 9)
                return 1+count;
        }
        if (cells[i][j] != 0)  // skip filled cells
            return solve(i+1,j,cells, count);
        // search for 2 solutions instead of 1
        // break, if 2 solutions are found
        for (int val = 1; val <= 9 && count < 2; ++val) {
            if (legal(i,j,val,cells)) {
                cells[i][j] = val;
                // add additional solutions
                count = solve(i+1,j,cells, count));
            }
        }
        cells[i][j] = 0; // reset on backtrack
        return count;
    }
    
    0 讨论(0)
提交回复
热议问题