我必须实现一种算法,为给定的边长(n=3,4)创建所有可能的幻方。对于 n=3,算法运行良好。但是对于 n=4,算法没有得到任何结果,因为它不是最优的(太慢了)。我试图优化算法,但它仍然无法正常工作。任何帮助是极大的赞赏。
public class MagicSquare {
private int[][] square;
private boolean[] possible;
private int totalSqs;
private int sum;
private static int numsquares;
public MagicSquare(int n){
square = new int[n][n];
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
square[i][j] = 0;
}
}
totalSqs = n*n;
possible = new boolean[totalSqs];
for(int i=0; i<totalSqs; i++)
possible[i] = true;
sum = n*(n*n+1)/2;
numsquares = 0;
fill(0, 0);
}
public void fill(int row, int col){
for(int i=0; i<totalSqs; i++){
if(possible[i]){
square[row][col] = i+1;
possible[i] = false;
int newcol = col+1;
int newrow = row;
if(newcol == square.length){
newrow++;
newcol = 0;
}
fill(newrow,newcol);
square[row][col] = 0;
possible[i] = true;
}
}
if(!checkRows() || !checkCols())
return;
if(row == square.length){
for(int i=0; i<square.length; i++ ){
for(int j=0; j<square[i].length; j++){
System.out.print(square[i][j]+" ");
}
System.out.println();
}
System.out.println();
numsquares++;
return;
}
}
public boolean checkRows(){
for(int i=0; i<square.length; i++){
int test = 0;
boolean unFilled = false;
for(int j=0; j<square[i].length; j++){
test += square[i][j];
if(square[i][j] == 0)
unFilled = true;
}
if(!unFilled && test!=sum)
return false;
}
return true;
}
public boolean checkCols(){
for(int j=0; j<square.length; j++){
int test = 0;
boolean unFilled = false;
for(int i=0; i<square[j].length; i++){
test += square[i][j];
if(square[i][j] == 0)
unFilled = true;
}
if(!unFilled && test!=sum)
return false;
}
return true;
}
public static void main(String[] args) {
new MagicSquare(3);
System.out.println(numsquares);
}
}