标签:
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.
对于这道题,我们需要试探着做,对于为“.”的地方,我们尝试不同的数字,看看这个是否是个有效的Sudoku,对于第11行,我们首先看是否是个有效的sudoku,然后再进行递归,如果对于之后的所有试探都是对的,那么就可以填写这个数,否则返回应该将该位置还原为“.”并尝试下一个数字,如果没有解,则返回false
1 public void solveSudoku(char[][] board) { 2 this.SudokuSingle(board); 3 } 4 private boolean SudokuSingle(char[][] board){ 5 for(int i=0;i<9;i++){ 6 for(int j=0;j<9;j++){ 7 char curr=board[i][j]; 8 if(curr==‘.‘){ 9 for(int k=1;k<=9;k++){ 10 board[i][j]=String.valueOf(k).charAt(0); 11 if(this.isValidSudoKu(board, i, j)&&this.SudokuSingle(board)) 12 { 13 return true; 14 } 15 board[i][j]=‘.‘; 16 } 17 return false; 18 } 19 } 20 } 21 return true; 22 } 23 private boolean isValidSudoKu(char[][] board,int row,int colum){ 24 for(int j=0;j<9;j++) 25 if(j != colum && board[row][j] == board[row][colum]) 26 return false; 27 28 for(int i=0;i<9;i++) 29 if(i != row && board[i][colum] == board[row][colum]) 30 return false; 31 32 int gridRow = row/3*3, gridCol = colum/3*3; 33 for(int i=0;i<3;i++) 34 for(int j=0;j<3;j++) 35 if(gridRow + i != row && gridCol + j != colum && board[gridRow + i][gridCol + j] == board[row][colum]) 36 return false; 37 return true; 38 }
标签:
原文地址:http://www.cnblogs.com/criseRabbit/p/4307325.html