Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character‘.‘
.
You may assume that there will be only one unique solution.
A Sudoku puzzle...
... And its solution numbers marked in red.
Problem: recursion. Try to place 0 ~ 9, and then recursively solve the remaining vacancies.
Write a public Boolean isvalidsudoku (char [] [] Board, int X, int y) function to determine whether the current number of boards (X, Y) is valid ), it only needs to check whether the elements of the same column and the same nine cells are repeated with those of the Board [x] [Y. (In fact, only four elements in the different columns of (x, y) and (x, y) are judged in the jiugongge, because we have already passed the same column of (x, y ).
The Code is as follows:
1 public class Solution { 2 public boolean isValidSudoku(char[][] board,int x,int y) { 3 //check for row x 4 for(int i = 0;i < 9;i++) 5 if(i!=y && board[x][i] == board[x][y]) 6 return false; 7 8 //check for column y 9 for(int i = 0;i < 9;i++)10 if(i!= x &&board[i][y] == board[x][y])11 return false;12 13 //check for the 3*3 square (x,y) belongs to14 for(int i = 3 * (x/3);i<3*(x/3)+3;i++){15 for(int j = 3*(y/3);j<3*(y/3)+3;j++){16 if(i!=x && j != y && board[i][j] == board[x][y] )17 return false;18 }19 }20 21 return true;22 }23 24 private boolean solveSudokuRecur(char[][] board){25 for(int i = 0;i < 9;i++){26 for(int j = 0;j < 9;j++){27 if(board[i][j] != ‘.‘)28 continue;29 for(int k = 1;k <= 9;k++){30 board[i][j] = (char)(k + ‘0‘);31 if(isValidSudoku(board,i,j) && solveSudokuRecur(board))32 return true;33 board[i][j] = ‘.‘;34 }35 return false;36 }37 }38 return true;39 }40 public void solveSudoku(char[][] board) {41 solveSudokuRecur(board);42 }43 }
Note that valid Sudoku is used to determine whether the entire Sudoku is valid, rather than whether a single location (X, Y) is valid. It needs to traverse the entire Sudoku, so this Code cannot be used.