实现一个3x3的九宫格,将1至9的数字填入方格,使得矩阵中心的元素为5,且每行每列及每个对角线的值相加都相同。 用Java
时间: 2024-10-21 18:04:25 浏览: 31
要在Java中实现一个满足条件的3x3九宫格,我们可以创建一个二维数组,并通过回溯算法来填充数字符合规则。这里是一个简单的示例代码:
```java
import java.util.ArrayList;
import java.util.List;
public class MagicSquare {
public static void main(String[] args) {
int[][] grid = new int[3][3];
fillGrid(grid, 5);
printGrid(grid);
}
// 回溯函数,尝试填充每个位置
private static boolean fillGrid(int[][] grid, int currentSum, int currentIndex) {
if (currentIndex == 9) { // 如果填满,检查是否满足条件
return checkMagicProperty(grid, currentSum);
}
for (int i = 1; i <= 9; i++) { // 尝试填下一个数字
if (isValidPosition(grid, currentIndex, i)) { // 检查当前位置是否有效
grid[currentIndex / 3][currentIndex % 3] = i; // 填充数字
if (fillGrid(grid, currentSum + i, currentIndex + 1)) { // 继续递归填充其他位置
return true;
}
grid[currentIndex / 3][currentIndex % 3] = 0; // 取消当前填充,回溯
}
}
return false; // 所有尝试都不满足条件,返回false
}
// 检查网格是否满足魔法性质(所有行、列和对角线的和相等)
private static boolean checkMagicProperty(int[][] grid, int sum) {
for (int i = 0; i < 3; i++) {
if (!checkRowSum(grid, i) || !checkColumnSum(grid, i) || !checkDiagonalSum(grid, i))
return false;
}
return true;
}
// 辅助方法检查某一行、列或对角线的和
private static boolean checkRowSum(int[][] grid, int row) {
int sum = 0;
for (int j = 0; j < 3; j++)
sum += grid[row][j];
return sum == sum % 9; // 对于3x3九宫格,和应该是9的倍数
}
private static boolean checkColumnSum(int[][] grid, int col) {
int sum = 0;
for (int i = 0; i < 3; i++)
sum += grid[i][col];
return sum == sum % 9;
}
private static boolean checkDiagonalSum(int[][] grid, int direction) {
int sum = 0;
if (direction == 0) { // 主对角线
for (int i = 0; i < 3; i++)
sum += grid[i][i];
} else { // 二级对角线
for (int i = 0; i < 3; i++)
sum += grid[i][2 - i];
}
return sum == sum % 9;
}
// 打印网格
private static void printGrid(int[][] grid) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.
阅读全文