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: 类似N-Queens问题, 一个个尝试填数,不行就回溯,直到填满返回。
如果对一个格子尝试从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 < board.length; i++) {
for(int j = 0; j < board[0].length; j++) {
if(board[i][j] == '.') {
for(char c = '1'; c <= '9'; c++) {
if(isValid(board, i, j, c)) { //try
board[i][j] = c;
if(helper(board)) {
return true;
}else {
board[i][j] = '.'; //go back
}
}
}
return false;
}
}
}
return true;
}
public boolean isValid(char[][] board, int i, int j, int c) {
for(int m = 0; m < 9; m++) { //check row
if(m != j && board[i][m] == c) {
return false;
}
}
for(int m = 0; m < 9; m++) { //check column
if(m != i && board[m][j] == c) {
return false;
}
}
for(int row = i/3*3; row < i/3*3+3; row++) { //check sub-boxes
for(int col = j/3*3; col < j/3*3+3; col++) {
if((row != i || col != j) && board[row][col] == c)
return false;
}
}
return true;
}
}
No comments:
Post a Comment