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 void solveSudoku(char[][] board) {
// Start typing your Java solution below
// DO NOT write main() function
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(int a=1;a<=9;a++) {
board[i][j] = (char) ((int)'0' + a);
if(isValid(board, i, j) && helper(board)) {
return true;
}
}
board[i][j] = '.';
return false;
}
}
}
return true;
}
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 j=0;j<9;j++) {
if(j!=n && board[m][j]==board[m][n]) {
return false;
}
}
for(int p=0;p<3;p++) {
for(int q=0;q<3;q++) {
int t = m/3*3+p;
int s = n/3*3+q;
if(!(t==m && s==n) && board[t][s]==board[m][n]) {
return false;
}
}
}
return true;
}
}
================
public class Solution {
public void solveSudoku(char[][] board) {
helper(board);
}
private 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 (check(board, i, j, c)) {
board[i][j] = c;
if (helper(board)) {
return true;
}
}
}
board[i][j] = '.';
return false;
}
}
}
return true;
}
private boolean check(char[][] board, int m, int n, char c) {
for (int i = 0; i < 9; i++) {
if (board[i][n] == c) {
return false;
}
}
for (int j = 0; j < 9; j++) {
if (board[m][j] == c) {
return false;
}
}
int x = m / 3;
int y = n / 3;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[x * 3 + i][y * 3 + j] == c) {
return false;
}
}
}
return true;
}
}
=============
public class Solution {
public void solveSudoku(char[][] board) {
helper(board);
}
private 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++) {
board[i][j] = c;
if (check(board, i, j, c) && helper(board)) {
return true;
}
}
board[i][j] = '.';
return false;
}
}
}
return true;
}
private boolean check(char[][] board, int i, int j, char c) {
for (int m = 0; m < 9; m++) {
if (board[i][m] == c && m != j) {
return false;
}
if (board[m][j] == c && m != i) {
return false;
}
int cubeRow = i / 3;
int cubeColumn = j / 3;
int x = m / 3;
int y = m % 3;
if (board[cubeRow * 3 + x][cubeColumn * 3 + y] == c && cubeRow * 3 + x != i && cubeColumn * 3 + y != j) {
return false;
}
}
return true;
}
}
没有评论:
发表评论