java编写一个程序创建一个9*9数独
时间: 2023-06-07 08:08:12 浏览: 162
矩阵,要求每行、每列和每个3*3小矩阵都有1-9的数字且不重复出现。能否提供解决方案?
当然可以。以下是Java编写的程序,可以创建一个9*9数独矩阵,确保每行、每列和每个3*3小矩阵都有1-9的数字且不重复出现:
```
public class Sudoku {
private int[][] board;
public Sudoku() {
board = new int[9][9];
}
public void generate() {
if (fillBoard(0, 0)) {
printBoard();
} else {
System.out.println("No solution found.");
}
}
private boolean fillBoard(int row, int col) {
if (col == 9) {
col = 0;
row++;
if (row == 9) {
return true;
}
}
if (board[row][col] != 0) {
return fillBoard(row, col + 1);
}
for (int num = 1; num <= 9; num++) {
if (isValid(num, row, col)) {
board[row][col] = num;
if (fillBoard(row, col + 1)) {
return true;
}
board[row][col] = 0;
}
}
return false;
}
private boolean isValid(int num, int row, int col) {
for (int i = 0; i < 9; i++) {
if (board[row][i] == num || board[i][col] == num) {
return false;
}
}
int startRow = row - row % 3;
int startCol = col - col % 3;
for (int i = startRow; i < startRow + 3; i++) {
for (int j = startCol; j < startCol + 3; j++) {
if (board[i][j] == num) {
return false;
}
}
}
return true;
}
private void printBoard() {
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
System.out.print(board[row][col] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Sudoku sudoku = new Sudoku();
sudoku.generate();
}
}
```
这个程序通过递归方式创建数独矩阵,确保每行、每列和每个3*3小矩阵都有1-9的数字且不重复出现。如果找到了解决方案,它会将该方案打印到控制台上。
阅读全文