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.
1 public class Solution { 2 public void solveSudoku(char[][] board) { 3 ArrayList<Integer> array=getArrayList(board); 4 DFS(board,array,0); 5 } 6 7 // store in the '.' location in the array 8 public ArrayList<Integer> getArrayList(char [][]board){ 9 ArrayList<Integer> array=new ArrayList<Integer>(); 10 for(int i=0;i<9;i++){ 11 for(int j=0;j<9;j++){ 12 if(board[i][j]=='.'){ 13 array.add(i*9+j); 14 } 15 } 16 } 17 return array; 18 } 19 20 public boolean DFS(char[][]board, ArrayList<Integer> array,int index){ 21 int len=array.size(); 22 // 当添的数目等于 '.' 的数目时候 depth到底 23 if(index == len) 24 return true; 25 int data=array.get(index); 26 int row=data/9; 27 int column=data%9; 28 // 将该格填入 1-9 29 for(int i=1;i<=9;i++){ 30 if(isValid(board, row, column, i)){ 31 board[row][column]=(char) (i+'0'); 32 if(DFS(board, array, index+1)) 33 return true; 34 // 如果添入的数不valid,把该格填'.' 35 board[row][column]='.'; 36 } 37 } 38 return false; 39 } 40 41 public boolean isValid(char[][]board,int row,int column,int data){ 42 for(int i=0;i<9;i++){ 43 if(board[row][i]-'0'==data) 44 return false; 45 if(board[i][column]-'0'==data) 46 return false; 47 int row_s=3*(row/3) + i/3; 48 int column_s=3*(column/3) + i%3; 49 if(board[row_s][column_s]-'0'==data) 50 return false; 51 } 52 return true; 53 } 54 }