1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| class Solution { public void solveSudoku(char[][] board) { backtricking(board); } private boolean backtricking(char[][] board){ for(int i = 0; i < 9;i++){ for(int j = 0; j < 9;j++){ if(board[i][j] != '.') continue; for(char k = '1'; k <= '9';k++){ if(isValidSudoku(i,j,k,board)){ board[i][j] = k; if(backtricking(board)) return true; board[i][j] = '.'; } } return false; } } return true; } public boolean isValidSudoku(int row, int col, char val, char[][] board){ for(int i = 0; i < 9;i++){ if(board[row][i] == val) return false; } for(int i = 0;i < 9;i++){ if(board[i][col] == val) return false; } int startRow = (row / 3) * 3; int startColumn = (col / 3) * 3; for(int i = startRow; i < startRow + 3;i++){ for(int j = startColumn; j < startColumn + 3;j++){ if(board[i][j] == val) return false; } } return true; } }
|