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.
Solution:
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 c = '1'; c <= '9'; c++) { if (isValid(board, i, j, c)) { board[i][j] = c; if (solve(board)) { return true; } else { board[i][j] = '.'; } } } return false; } } } return true; } public boolean isValid(char[][] board, int row, int col, char c) { for (int i = 0; i < 9; i++) { if (board[row][i] != '.' && board[row][i] == c) { return false; } if (board[i][col] != '.' && board[i][col] == c) { return false; } int rowIndex = (row / 3) * 3 + i / 3; int columnIndex = (col / 3) * 3 + i % 3; if (board[rowIndex][columnIndex] != '.' && board[rowIndex][columnIndex] == c) { return false; } } return true; }新闻热点
疑难解答