6X6数独 java
时间: 2024-02-09 15:06:15 浏览: 154
6x6数独是一种基于数字的逻辑游戏,目标是在一个6x6的方格中填入数字1到6,使得每一行、每一列和每个3x2的小方格内都包含了1到6的数字,且每个数字在每一行、每一列和每个小方格内都只出现一次。
以下是一个简单的Java代码示例,用于解决6x6数独问题:
```java
public class SudokuSolver {
private int[][] grid;
public SudokuSolver(int[][] grid) {
this.grid = grid;
}
public boolean solve() {
for (int row = 0; row < 6; row++) {
for (int col = 0; col < 6; col++) {
if (grid[row][col] == 0) {
for (int num = 1; num <= 6; num++) {
if (isValid(row, col, num)) {
grid[row][col] = num;
if (solve()) {
return true;
}
grid[row][col] = 0;
}
}
return false;
}
}
}
return true;
}
private boolean isValid(int row, int col, int num) {
for (int i = 0; i < 6; i++) {
if (grid[row][i] == num || grid[i][col] == num) {
return false;
}
}
int startRow = row - row % 2;
int startCol = col - col % 3;
for (int i = startRow; i < startRow + 2; i++) {
for (int j = startCol; j < startCol + 3; j++) {
if (grid[i][j] == num) {
return false;
}
}
}
return true;
}
public void printSolution() {
for (int row = 0; row < 6; row++) {
for (int col = 0; col < 6; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] grid = {
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0}
};
SudokuSolver solver = new SudokuSolver(grid);
if (solver.solve()) {
solver.printSolution();
} else {
System.out.println("No solution exists.");
}
}
}
```
这段代码使用递归的方式来解决数独问题。它通过尝试在每个空格中填入数字,并检查是否满足数独的规则,如果满足则继续递归地解决下一个空格,直到所有空格都被填满或者无解。
阅读全文