我正試圖編寫一個程序,可以爲固定的N維生成所有可能的幻方塊。我將通過用值填充對角線單元格然後用值填充行來解決這個問題。Magic Square遞歸無限循環java
我似乎陷入了無限循環時填入行,但似乎無法弄清楚如何或爲什麼。我沒有執行總和檢查,以檢查行或列的總和是否正確,但這在這裏是無關緊要的。
如果有人能幫助我,我會非常感激。 代碼波紋管
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);
}
}
你調試過嗎?哪種方法會卡住? – talnicolas 2012-03-22 15:10:12
它填滿行時卡住了。我確信對角線方法是正確的。我測試了他們,他們按照想象工作。編輯:回答,它卡在行(int x,int y);方法。 – Mythril225 2012-03-22 15:12:00
嗯,我不確定你是否正在遞歸調用'row(x + 1,y);'永遠。 – talnicolas 2012-03-22 15:17:28