classSolution{// box sizeint n =3;// row sizeint N = n * n;int[][] rows =newint[N][N +1];int[][] columns =newint[N][N +1];int[][] boxes =newint[N][N +1];char[][] board;boolean sudokuSolved =false;publicbooleancouldPlace(int d,int row,int col){/*
Check if one could place a number d in (row, col) cell
*/int idx =(row / n )* n + col / n;return rows[row][d]+ columns[col][d]+ boxes[idx][d]==0;}publicvoidplaceNumber(int d,int row,int col){/*
Place a number d in (row, col) cell
*/int idx =(row / n )* n + col / n;
rows[row][d]++;
columns[col][d]++;
boxes[idx][d]++;
board[row][col]=(char)(d +'0');}publicvoidremoveNumber(int d,int row,int col){/*
Remove a number which didn't lead to a solution
*/int idx =(row / n )* n + col / n;
rows[row][d]--;
columns[col][d]--;
boxes[idx][d]--;
board[row][col]='.';}publicvoidplaceNextNumbers(int row,int col){/*
Call backtrack function in recursion
to continue to place numbers
till the moment we have a solution
*/// if we're in the last cell// that means we have the solutionif((col == N -1)&&(row == N -1)){
sudokuSolved =true;}// if not yetelse{// if we're in the end of the row// go to the next rowif(col == N -1)backtrack(row +1,0);// go to the next columnelsebacktrack(row, col +1);}}publicvoidbacktrack(int row,int col){/*
Backtracking
*/// if the cell is emptyif(board[row][col]=='.'){// iterate over all numbers from 1 to 9for(int d =1; d <10; d++){if(couldPlace(d, row, col)){placeNumber(d, row, col);placeNextNumbers(row, col);// if sudoku is solved, there is no need to backtrack// since the single unique solution is promisedif(!sudokuSolved)removeNumber(d, row, col);}}}elseplaceNextNumbers(row, col);}publicvoidsolveSudoku(char[][] board){this.board = board;// init rows, columns and boxesfor(int i =0; i < N; i++){for(int j =0; j < N; j++){char num = board[i][j];if(num !='.'){int d = Character.getNumericValue(num);placeNumber(d, i, j);}}}backtrack(0,0);}}
作者:LeetCode
链接:https://leetcode-cn.com/problems/sudoku-solver/solution/jie-shu-du-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。