解题思路:
枚举法
import java.util.Scanner;
//枚举法,采用枚举的方式存储不同的九宫格排列
public class Main {
// 定义九个不同的九宫格排列
public static int[][] exp = {
{ 4, 9, 2, 3, 5, 7, 8, 1, 6 },
{ 8, 3, 4, 1, 5, 9, 6, 7, 2 },
{ 6, 1, 8, 7, 5, 3, 2, 9, 4 },
{ 2, 7, 6, 9, 5, 1, 4, 3, 8 },
{ 2, 9, 4, 7, 5, 3, 6, 1, 8 },
{ 6, 7, 2, 1, 5, 9, 8, 3, 4 },
{ 8, 1, 6, 3, 5, 7, 4, 9, 2 },
{ 4, 3, 8, 9, 5, 1, 2, 7, 6 }
};
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] arr = new int[9];
// 读取用户输入的九宫格数字
for (int i = 0; i < 9; i++) {
arr[i] = scan.nextInt();
}
int cnt = 0;
int position = 0;
// 遍历不同的九宫格排列,查看是否和用户输入一致
for (int i = 0; i < 8; i++) {
int flag = 1;
for (int j = 0; j < 9; j++) {
if (arr[j] != 0 && arr[j] != exp[i][j]) {
flag = 0;
break;
}
}
if (flag == 1) {
cnt++;
position = i;
}
}
//输出
if (cnt == 1) {
for (int i = 0; i < 9; i++) {
System.out.print(exp[position][i]);
//i从0开始,判断换行时需要加1
if ((i + 1) % 3 == 0) System.out.println();
else System.out.print(" ");
}
} else {
System.out.print("Too Many");
}
}
}