37. Sudoku Solver
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.
public class Solution {
public void solveSudoku(char[][] board) {
solve(board, 0);
}
private boolean solve(char[][] b, int pos){
int row= pos/9;
int col= pos%9;
int[] box= {row/3, col/3};
if (pos== 81)
return true;
if (b[row][col] != '.'){
if (solve(b, pos+1))
return true;
}
else{
for (int i = 1; i <= 9; i++) {
String s= String.valueOf(i);
char ch= s.charAt(0);
if (CheckRow(b, row, ch)
&& CheckColumn(b, col, ch)
&& CheckBox(b, box, ch)){
b[row][col]= ch;
if (solve(b, pos+1))
return true;
b[row][col]= '.';
}
}
}
return false;
}
public boolean CheckRow(char[][] b, int row, char num) {
for (int i = 0; i < 9; i++) {
if (b[row][i] == num)
return false;
}
return true;
}
public boolean CheckColumn(char[][] b, int column, char num) {
for (int i = 0; i < 9; i++) {
if (b[i][column] == num)
return false;
}
return true;
}
public boolean CheckBox(char[][] b, int[] boxNum, char num){
for (int row = 0; row < 3; row++) {
for (int column = 0; column < 3; column++) {
int currentRow= row+ 3*boxNum[0];
int currentColumn= column+ 3*boxNum[1];
if (b[currentRow][currentColumn] == num)
return false;
}
}
return true;
}
}