使用java代码,实现数独。需要根据9X9盘面上的已知数字,推算出所有剩余空格的数字,并且满足每一行、每一列、每一个3X3粗线宫内的数字均含1-9,并且不重复。
时间: 2023-05-18 12:03:30 浏览: 99
java实现数独游戏(九宫格)
5星 · 资源好评率100%
以下是一个使用Java代码实现数独的示例:
```java
public class SudokuSolver {
private int[][] board;
public SudokuSolver(int[][] board) {
this.board = board;
}
public boolean solve() {
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
if (board[row][col] == 0) {
for (int num = 1; num <= 9; num++) {
if (isValid(row, col, num)) {
board[row][col] = num;
if (solve()) {
return true;
} else {
board[row][col] = 0;
}
}
}
return false;
}
}
}
return true;
}
private boolean isValid(int row, int col, int num) {
for (int i = 0; i < 9; i++) {
if (board[row][i] == num || board[i][col] == num) {
return false;
}
}
int boxRow = row - row % 3;
int boxCol = col - col % 3;
for (int i = boxRow; i < boxRow + 3; i++) {
for (int j = boxCol; j < boxCol + 3; j++) {
if (board[i][j] == num) {
return false;
}
}
}
return true;
}
public void print() {
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
System.out.print(board[row][col] + " ");
}
System.out.println();
}
}
}
```
你可以使用以下代码来测试:
```java
public static void main(String[] args) {
int[][] board = {
{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}
};
SudokuSolver solver = new SudokuSolver(board);
if (solver.solve()) {
solver.print();
} else {
System.out.println("No solution found.");
}
}
```
输出结果应该是:
```
5 3 4 6 7 8 9 1 2
6 7 2 1 9 5 3 4 8
1 9 8 3 4 2 5 6 7
8 5 9 7 6 1 4 2 3
4 2 6 8 5 3 7 9 1
7 1 3 9 2 4 8 5 6
9 6 1 5 3 7 2 8 4
2 8 7 4 1 9 6 3 5
3 4 5 2 8 6 1 7 9
```
阅读全文