数独问题求解
数独问题求解
package p1;
/**
* 数独问题求解
* @author Guozhu Zhu
* @date 2019/4/16
* @version 1.0
*
*/
public class Shudu01 {
/* =========== Test =========== */
public static void main(String[] args) {
char[][] board = new char[][] {
{'1', '.', '.', '.', '.', '.', '.', '.', '.'},
{'2', '.', '.', '.', '.', '.', '.', '.', '.'},
{'3', '.', '.', '.', '.', '.', '.', '.', '.'},
{'4', '.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.', '.'},
{'.', '.', '.', '.', '.', '.', '.', '.', '.'}
};
printBoard(board);
System.out.println("====================================");
solveShuDu(board);
boolean ans = isValidShudu(board);
System.out.println("isValidShudu:" + ans);
System.out.println("====================================\n");
printBoard(board);
}
//printBoard
public static void printBoard(char[][] board) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " | ");
}
System.out.println("");
System.out.println("----------------------------------");
}
}
public static boolean solveShuDu(char[][] board) {
//mark rows flag
boolean[][] rows = new boolean[9][10];
//mark cols flag
boolean[][] cols = new boolean[9][10];
//mark board flag
boolean[][] blocks = new boolean[9][10];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
//当前位置不为空(.)
if (board[i][j] != '.') {
int num = board[i][j] - '0';
rows[i][num] = true;
cols[j][num] = true;
blocks[i/3*3 + j/3][num] = true;
}
}
}
return dfs(board, rows, cols, blocks, 0, 0);
}
public static boolean dfs(char[][] board, boolean[][] rows, boolean[][] cols, boolean[][] blocks, int i, int j) {
//查找空位置
while (board[i][j] != '.') {
if (++j >= 9) {
i++;
j = 0;
}
if (i >= 9) {
return true;
}
}
for (int num = 1; num <= 9; num++) {
int blockIdx = (i/3*3 + j / 3);
//当前位置可以放的情况
if (!rows[i][num] && !cols[j][num] && !blocks[blockIdx][num]) {
board[i][j] = (char)('0'+num);
rows[i][num] = true;
cols[j][num] = true;
blocks[blockIdx][num] = true;
if (dfs(board, rows, cols, blocks, i, j) == true) {
return true;
} else {
board[i][j] = '.';
rows[i][num] = false;
cols[j][num] = false;
blocks[blockIdx][num] = false;
}
}
}
return false;
}
//判断是否是有效的数独
public static boolean isValidShudu(char[][] board) {
boolean[][] rows = new boolean[9][10];
boolean[][] cols = new boolean[9][10];
boolean[][] blocks = new boolean[9][10];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != '.') {
int num = board[i][j] - '0';
if (rows[i][num] && cols[j][num] && blocks[i/3*3 + j/3][num]) {
return false;
} else {
//初始设置
rows[i][num] = true;
cols[j][num] = true;
blocks[i/3*3 + j/3][num] = true;
}
}
}
}
return true;
}
}