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...
与n皇后问题类似, 对于每个空格逐步添加数字, 不对了就回溯
如果对一个格子尝试从0~9都不行,那么说明整个sudoku无解,返回false
对整个棋盘所有'.'都填完了,返回true
public class Solution {
public void solveSudoku(char[][] board) {
if (board == null || board.length < 9 || board[0].length < 9) {
return;
}
helper(board);
}
public boolean helper(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 (helper(board)) {
return true;
} else {
board[i][j] = '.';
}
}
}
return false;
}
}
}
return true;
}
public boolean isValid(char[][] board, int i, int j, char c) {
//check column
for (int row = 0; row < 9; row ++) {
if (board[row][j] == c) {
return false;
}
}
// check row
for (int column = 0; column < 9; column++) {
if (board[i][column] == c) {
return false;
}
}
//check block
for (int row = i / 3 * 3; row < i / 3 * 3 + 3; row++) {
for(int column = j / 3 * 3; column < j / 3 * 3 + 3; column++) {
if (board[row][column] == c) {
return false;
}
}
}
return true;
}
}
//
public class Solution {
public void solveSudoku(char[][] board) {
helper(board, 0, 0);
}
public boolean helper(char[][] board, int m, int n) {
if (n >= 9) {
return helper(board, m + 1, 0);
}
if (m == 9) {
return true;
}
if (board[m][n] == '.') {
for (int i = 1; i <= 9; i++) {
board[m][n] = (char)(i + '0');
if (isvalid(board, m, n)) {
if (helper(board, m, n+ 1)) {
return true;
}
}
board[m][n] = '.';
}
} else {
return helper(board, m, n+ 1);
}
return false;
}
public boolean isvalid(char[][] board, int m, int n) {
for (int i = 0; i < 9; i++) {
if (i != m && board[i][n] == board[m][n]) {
return false;
}
}
for (int i = 0; i < 9; i++) {
if (i != n && board[m][i] == board[m][n]) {
return false;
}
}
for (int i = m / 3 * 3; i< m / 3 * 3 + 3; i++) {
for (int j = n /3 * 3; j < n / 3 *3 + 3; j++) {
if (i != m && j != n && board[i][j] == board[m][n]) {
return false;
}
}
}
return true;
}
}
没有评论:
发表评论