用java编写一个程序,在一个3*3的表格中分别填入1至9的数,使每行、每列、对角线上的3个数之和都等于15。
时间: 2024-05-05 13:15:36 浏览: 12
思路:
- 首先我们可以枚举出1~9的全排列,然后依次填入表格中。
- 在填写过程中,我们可以实时计算每行、每列、每个对角线上的和并与15进行比较,如果不相等就撤销当前填写并换下一个数字。
- 如果最终所有格子都填写完毕并且满足条件,就输出结果。
代码实现:
```java
public class MagicSquare {
private static final int N = 3;
private static final int SUM = 15;
private static int[][] table = new int[N][N];
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
permute(nums, 0);
}
private static void permute(int[] nums, int start) {
if (start == nums.length) {
if (check()) {
print();
}
} else {
for (int i = start; i < nums.length; i++) {
swap(nums, start, i);
permute(nums, start + 1);
swap(nums, start, i);
}
}
}
private static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
private static boolean check() {
// check rows
for (int i = 0; i < N; i++) {
int sum = 0;
for (int j = 0; j < N; j++) {
sum += table[i][j];
}
if (sum != SUM) {
return false;
}
}
// check columns
for (int j = 0; j < N; j++) {
int sum = 0;
for (int i = 0; i < N; i++) {
sum += table[i][j];
}
if (sum != SUM) {
return false;
}
}
// check diagonals
int sum1 = 0, sum2 = 0;
for (int i = 0; i < N; i++) {
sum1 += table[i][i];
sum2 += table[i][N - i - 1];
}
if (sum1 != SUM || sum2 != SUM) {
return false;
}
return true;
}
private static void print() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(table[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
}
```
输出结果:
```
8 1 6
3 5 7
4 9 2
6 1 8
7 5 3
2 9 4
4 9 2
3 5 7
8 1 6
2 9 4
7 5 3
6 1 8
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)