我正在尝试编写一个程序,该程序可以为固定的 N 维生成所有可能的幻方。我将通过用值填充对角线单元格然后用值填充行来解决这个问题。
填写行时,我似乎陷入了无限循环,但似乎无法弄清楚如何或为什么。我还没有实现总和检查,以检查行或列的总和是否正确,但这在这里无关紧要。
如果有人可以帮助我,我会非常感激。代码如下
public class Magic {
public static final int DIMENSION = 3;
public static final int DIMSQ = DIMENSION * DIMENSION;
public static int[][] array = new int[DIMENSION][DIMENSION];
public static boolean[] boolArray = new boolean[DIMENSION * DIMENSION];
public static final int sum = (DIMENSION * (DIMENSION * DIMENSION + 1)) / 2;
/*
* Inicializaljuk a matrixunkat, illetve a boolean matrixunkat
* Initializes the matrix and boolArray with values.
*/
public static void init() {
for (int e[] : array) {
for (int e2 : e) {
e2 = 0;
}
}
for (boolean e : boolArray) {
e = false;
}
}
/*
* Ki irassa a matrix jelenlegi allapotat konzolra
* Prints the array out to the console.
*/
public static void print() {
for (int i[] : array) {
for (int j : i) {
System.out.print(j + ",");
}
System.out.println();
}
System.out.println();
}
/*
* feltolti a foatlot adatokkal, majd meghivja a diagonal2-t
* fills diagonal cells with values
*/
public static void diagonal1(int x) {
for (int i = 0; i < DIMSQ; i++) {
if (!boolArray[i]) {
boolArray[i] = true;
array[x][x] = i + 1;
if (x < DIMENSION - 1) {
diagonal1(x + 1);
} else
diagonal2(0);
boolArray[i] = false;
}
}
}
/*
* feltolti a mellekatlot adatokkal, majd meghivja a row(0,0,0)-t
* fills diagonal cells with values
*/
public static void diagonal2(int x) {
for (int i = 0; i < DIMSQ; i++) {
if (!boolArray[i]) {
if (array[DIMENSION - 1 - x][x] == 0) {
boolArray[i] = true;
array[DIMENSION - 1 - x][x] = i + 1;
}
if (x < DIMENSION - 1) {
diagonal2(x + 1);
} else
row(0, 0);
boolArray[i] = false;
}
}
}
/*
* feltolti a sorokat adatokkal
* fills rows with values
*/
public static void row(int x, int y) {
for (int i = 0; i < DIMSQ; i++) {
if (!boolArray[i]) {
if (array[x][y] == 0) {
boolArray[i] = true;
array[x][y] = i;
}
if (x < DIMENSION - 1) {
row(x + 1, y);
} else if(y < DIMENSION - 1) {
row(0,y+1);
} else print();
boolArray[i] = false;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
init();
print();
diagonal1(0);
}
}