我用蛮力方法尝试了这个问题,它有效。
生成一个独特的 9 x 9 板用了不到 1 秒。
输出:
1 2 3 4 5 6 7 8 9
2 6 8 9 7 4 1 3 5
6 3 5 7 9 1 2 4 8
9 5 4 8 6 2 3 1 7
5 4 7 1 2 8 9 6 3
8 1 9 6 3 7 5 2 4
4 9 2 3 8 5 6 7 1
7 8 6 5 1 3 4 9 2
3 7 1 2 4 9 8 5 6
以下是我的代码:
public static void main(String[] args){
int size = 9;
int[][] board= new int[size][size];
board[0] = Util.createOrderedArray(size, 1);
for(int x=1; x<size; x++){
board[x] = Util.createOrderedArray(size, 1);
do{
Util.shuffle(board[x]);
}while(!Util.compare2DArray(board[x], board, 0, x));
}
Util.print(board);
}
我在一个自定义的 Util 类中编写了所有的辅助方法。
final class Util
{
public static void shuffle(int[] num){
Random rnd = new Random();
for(int x=0; x<num.length; x++)
swap(num, x, rnd.nextInt(num.length));
}
public static void swap(int[] num, int a, int b){
int temp = num[a];
num[a] = num[b];
num[b] = temp;
}
public static int[] createOrderedArray(int size, int startValue){
int[] num = new int[size];
for(int x=0; x<num.length; x++)
num[x] = x+startValue;
return num;
}
//Return TRUE if array vs arrays is COMPLETELY different
public static boolean compare2DArray(int[] num1, int[][] num2, int start, int end){
for(int x=start; x<end; x++)
if(!compareArray(num1, num2[x]))
return false;
return true;
}
//Return TRUE if arrays are COMPLETELY different
public static boolean compareArray(int[] num1, int[] num2){
if(num1.length != num2.length)
return false;
for(int x=0; x<num1.length; x++)
if(num1[x] == num2[x])
return false;
return true;
}
public static void print(int[][] num){
for(int x=0; x<num.length; x++){
for(int y=0; y<num[0].length; y++)
System.out.print(num[x][y] + " ");
System.out.println("");
}
}
}
这是通过蛮力方法完成的。如果你想优雅地做,我们递归做会更有效率,所以不会浪费不必要的循环。