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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| public class SudokuSolver { public void solveSudoku(char[][] board) { solve(board); }
private boolean solve(char[][] board) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (board[i][j] == '*') { for (char num = '1'; num <= '9'; num++) { if (isValid(board, i, j, num)) { board[i][j] = num; if (solve(board)) { return true; } else { board[i][j] = '*'; } } } return false; } } } return true; }
private boolean isValid(char[][] board, int row, int col, char num) { for (int i = 0; i < 9; i++) { if (board[row][i] == num || board[i][col] == num || board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == num) { return false; } } return true; }
public static void main(String[] args) { char[][] board = { {'*','4','*', '*','*','3', '*','*','1'}, {'3','*','*', '5','*','*', '*','9','*'}, {'*','*','6', '*','7','*', '*','*','*'},
{'*','2','*', '*','8','4', '*','*','*'}, {'*','*','*', '*','6','*', '*','4','*'}, {'*','*','7', '*','*','*', '*','5','*'},
{'2','*','*', '6','*','*', '9','*','*'}, {'*','*','*', '*','*','*', '4','*','*'}, {'9','*','5', '1','*','*', '*','*','2'} };
SudokuSolver solver = new SudokuSolver(); solver.solveSudoku(board);
for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { System.out.print(board[i][j] + " "); } System.out.println(); } } }
|