用Java编码实现,一个数独程序,输入一个一共用九行九列表示九宫格,每行数字以{开始,}结束,数字之间用逗号分隔,已知数字位用X表示,1≤X≤9,空缺位以数字0表示,输出一个包含所有数字的九宫格,与输入格式相同,结尾不包含空行,给出完整代码
时间: 2024-09-27 18:06:27 浏览: 37
在Java中编写一个简单的数独求解器,可以采用递归回溯法。以下是一个基本的数独解决方案,先解析输入,然后填充数独并检查每一行、每一列以及每个小宫格是否满足规则:
```java
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SudokuSolver {
private static final int SIZE = 9;
private static final String[] DIRECTIONS = { "0,1,2", "3,4,5", "6,7,8" };
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入数独的初始状态(以{开始,}结束): ");
String input = scanner.nextLine();
// 解析输入字符串
String[][] board = parseInput(input);
if (solveSudoku(board)) {
printBoard(board);
} else {
System.out.println("无法完成数独填写");
}
scanner.close();
}
// 解析输入
private static String[][] parseInput(String input) {
Pattern pattern = Pattern.compile("\\{(\\d+,)*\\}");
Matcher matcher = pattern.matcher(input);
String[] parts = matcher.group().split(",");
String[][] board = new String[SIZE][SIZE];
for (int i = 0; i < SIZE; i++) {
String[] rowParts = parts[i * SIZE].split(",");
for (int j = 0; j < SIZE; j++) {
if (!rowParts[j].equals("X")) {
board[i][j] = rowParts[j];
} else {
board[i][j] = "0";
}
}
}
return board;
}
// 检查并填充数独
private static boolean solveSudoku(String[][] board) {
int[] row, col, box;
for (int r = 0; r < SIZE; r++) {
for (int c = 0; c < SIZE; c++) {
if (board[r][c].equals("0")) {
row = getRow(r);
col = getCol(c);
box = getBox(r, c);
for (int num = 1; num <= SIZE; num++) {
if (isValid(board, r, c, num)) {
board[r][c] = Integer.toString(num);
if (solveSudoku(board)) {
return true;
} else {
board[r][c] = "0"; // 回溯
}
}
}
return false;
}
}
}
return true;
}
// 判断当前位置填入数字是否合法
private static boolean isValid(String[][] board, int r, int c, int num) {
// 检查行、列和宫格
return !getRow(r).contains(Integer.toString(num))
&& !getCol(c).contains(Integer.toString(num))
&& !getBox(r, c).contains(Integer.toString(num));
}
// 获取行、列和宫格数组
private static String[] getRow(int row) {
return board[row];
}
private static String[] getCol(int col) {
String[] colArray = new String[SIZE];
for (int i = 0; i < SIZE; i++) {
colArray[i] = board[i][col];
}
return colArray;
}
private static String[] getBox(int r, int c) {
int boxStartR = (r / 3) * 3;
int boxStartC = (c / 3) * 3;
String[] boxArray = new String[3 * 3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
boxArray[i + j * 3] = board[boxStartR + i][boxStartC + j];
}
}
return boxArray;
}
// 打印数独
private static void printBoard(String[][] board) {
StringBuilder output = new StringBuilder();
for (String[] row : board) {
for (String cell : row) {
output.append(cell).append(",");
}
output.append("{\n");
if (row.length != 0) {
output.deleteCharAt(output.length() - 1); // 删除最后一个逗号
}
}
output.deleteCharAt(output.length() - 2); // 删除最后一行的}
output.append("}\n\n");
System.out.print(output);
}
}
阅读全文