标签:style blog http io ar color sp for on
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.
Solution:
http://blog.csdn.net/zxzxy1988/article/details/8586289
1 public class Solution { 2 public void solveSudoku(char[][] board) { 3 mySudokuSolver(board); 4 } 5 6 private boolean mySudokuSolver(char[][] board) { 7 // TODO Auto-generated method stub 8 for(int i=0;i<board.length;++i){ 9 for(int j=0;j<board[0].length;++j){ 10 if(board[i][j]==‘.‘){ 11 for(int k=1;k<=9;++k){ 12 board[i][j]=(char) (k+‘0‘); 13 if(isValid(board,i,j)&&mySudokuSolver(board)){ 14 return true; 15 } 16 board[i][j]=‘.‘; //这里这个细节不要忘掉!!,你把后边儿的“.“改成数字后,发现做不下去了,得回溯,那你
//得把这个数字改回"."啊
17 } 18 return false; 19 } 20 } 21 } 22 return true; 23 } 24 25 private boolean isValid(char[][] board, int row, int col) { 26 // TODO Auto-generated method stub 27 for(int i=0;i<board.length;++i){ 28 if(i!=row&&board[i][col]==board[row][col]) 29 return false; 30 } 31 for(int i=0;i<board[0].length;++i){ 32 if(i!=col&&board[row][i]==board[row][col]) 33 return false; 34 } 35 for(int i=(row/3)*3;i<(row/3+1)*3;++i){ 36 for(int j=(col/3)*3;j<(col/3+1)*3;++j){ 37 if(i!=row&&j!=col&&board[i][j]==board[row][col]) 38 return false; 39 } 40 } 41 return true; 42 } 43 }
标签:style blog http io ar color sp for on
原文地址:http://www.cnblogs.com/Phoebe815/p/4137277.html