1 public class Solution { 2 public void solveSudoku(char[][] board) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 solveSudokuRecursive(board); 6 } 7 private boolean solveSudokuRecursive(char[][] board) { 8 int[] pairs = getFirstEmpty(board); 9 if (pairs[0] == -1 && pairs[1] == -1) 10 return true; 11 for (int i = 1; i <= 9; i++) { 12 board[pairs[0]][pairs[1]] = (char) (i + '0'); 13 if (isValid(board, pairs[0], pairs[1]) 14 && solveSudokuRecursive(board)) { 15 return true; 16 } 17 board[pairs[0]][pairs[1]] = '.'; 18 } 19 return false; 20 } 21 22 private int[] getFirstEmpty(char[][] board) { 23 int[] pairs = null; 24 for (int i = 0; i < 9; i++) { 25 for (int j = 0; j < 9; j++) { 26 if (board[i][j] == '.') { 27 pairs = new int[] { i, j }; 28 return pairs; 29 } 30 } 31 } 32 pairs = new int[] { -1, -1 }; 33 return pairs; 34 } 35 36 37 private boolean isValid(char[][] board, int x, int y) { 38 39 for (int i = 0; i < 9; i++) { 40 if (i != y && board[x][i] == board[x][y]) 41 return false; 42 43 if (i != x && board[i][y] == board[x][y]) 44 return false; 45 } 46 47 int xIdx = (x / 3) * 3; 48 int yIdx = (y / 3) * 3; 49 for (int m = 0; m < 3; m++) { 50 for (int n = 0; n < 3; n++) { 51 if(m + xIdx != x && n + yIdx != y && board[m + xIdx][n + yIdx] == board[x][y]) 52 return false; 53 } 54 } 55 return true; 56 } 57 }