37. Sudoku Solver
class Solution { public void solveSudoku(char[][] board) { boolean[][][] used=new boolean[3][9][9]; for(int i=0;i<9;i++) for(int j=0;j<9;j++) if(board[i][j]!='.') { int idx=(int)board[i][j]-'1'; used[0][i][idx]=true; used[1][j][idx]=true; int k=i/3*3+j/3; used[2][k][idx]=true; } dfs(board,used); } private boolean dfs(char[][] board, boolean[][][] used) { int row=-1; int col=-1; boolean found=false; for(int i=0;i<9;i++) for(int j=0;j<9;j++) if(board[i][j]=='.'&&found==false) { row=i; col=j; found=true; } if(found==false) return true; int k=row/3*3+col/3; for(int idx=0;idx<9;idx++) if(used[0][row][idx]==false&&used[1][col][idx]==false&&used[2][k][idx]==false) { board[row][col]=(char)('1'+idx); used[0][row][idx]=true; used[1][col][idx]=true; used[2][k][idx]=true; if(dfs(board,used)==true) return true; board[row][col]='.'; used[0][row][idx]=false; used[1][col][idx]=false; used[2][k][idx]=false; } return false; } }