编写一个程序,通过已填充的空格来解决数独问题。
一个数独的解法需遵循如下规则:
数字 1-9 在每一行只能出现一次。数字 1-9 在每一列只能出现一次。数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
空白格用 '.' 表示。
一个数独。
答案被标成红色。
Note:
给定的数独序列只包含数字 1-9 和字符 '.' 。你可以假设给定的数独只有唯一解。给定数独永远是 9x9 形式的。
package leetCode5_20;
/**
* @author : caoguotao
* @date 创建时间:2019年5月23日 下午10:53:05
* @version 1.0
* @parameter
* @since
* @return
*/
public class Solution37 {
public static void main(String[] args) {
char[][] board = new char[][]{
{'5', '3', '.', '.', '7', '.', '.', '.', '.'},
{'6', '.', '.', '1', '9', '5', '.', '.', '.'},
{'.', '9', '8', '.', '.', '.', '.', '6', '.'},
{'8', '.', '.', '.', '6', '.', '.', '.', '3'},
{'4', '.', '.', '8', '.', '3', '.', '.', '1'},
{'7', '.', '.', '.', '2', '.', '.', '.', '6'},
{'.', '6', '.', '.', '.', '.', '2', '8', '.'},
{'.', '.', '.', '4', '1', '9', '.', '.', '5'},
{'.', '.', '.', '.', '8', '.', '.', '7', '9'}
};
solveSudoku(board);
}
private static void printBoard(char[][] board) {
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
public static void solveSudoku(char[][] board) {
//记录行
boolean[][] rows = new boolean[9][10];
//记录列
boolean[][] cols = new boolean[9][10];
//记录3*3
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;
}
}
}
dfs(board, rows, cols, blocks, 0 , 0);
printBoard(board);
}
public static boolean dfs(char[][] board, boolean[][] rows, boolean[][] cols, boolean[][] blocks, int i, int j) {
//找到.,代表还没有填数字
while(board[i][j] != '.') {
if(++i >= 9) {
j++;
i = 0;
}
if(j >= 9) {
return true;
}
}
//填入数据
for(int num = 1; num <= 9; num++) {
if(rows[i][num] || cols[j][num] || blocks[i /3 *3 + j / 3][num]) {
}else {
board[i][j] = (char) (num + '0');
rows[i][num] = true;
cols[j][num] = true;
blocks[i / 3 * 3 + j / 3][num] = true;
if(dfs(board, rows, cols, blocks, i, j)) {
return true;
}else {
rows[i][num] = false;
cols[j][num] = false;
blocks[i / 3 * 3 + j / 3][num] = false;
board[i][j] = '.';
}
}
}
return false;
}
}