最近在学习数据结构与算法这块,参考别人的代码,自己写了一遍回溯算法的八皇后实现,记录一下,以备自己复习。
不多说了,直接上代码。
public class Backtrack8Queens {
private static int[][] result = new int[8][8];
public static void main(String[] args) {
System.out.println("hello,world!");
calc8queens(0);
}
public static void calc8queens(int row) {
if(row == 8) {
print8queens(result);
return;
}
for(int col = 0; col < 8; ++col) {
if(check(row, col)) {
result[row][col] = 1;
calc8queens(row + 1);
result[row][col] = 0;
}
}
}
public static boolean check(int row, int col) {
int leftup = col - 1;
int rightup = col + 1;
for(int i = row - 1; i >= 0; --i) {
if(result[i][col] == 1) return false;
if(leftup >= 0 && result[i][leftup] == 1) return false;
if(rightup < 8 && result[i][rightup] == 1) return false;
--leftup;
++rightup;
}
return true;
}
public static void print8queens(int[][] result) {
for(int i = 0; i < result.length; ++i) {
for(int j = 0; j < result[0].length; ++j) {
System.out.print(String.format("%s\t", result[i][j]));
}
System.out.println();
}
System.out.println();
}
}
运行结果如下:
hello,world!
1 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0
0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1
0 0 1 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 1 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 1 0 0 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1
0 0 1 0 0 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 1 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 1 0
1 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 1 0 0
0 0 0 1 0 0 0 0
0 1 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 1 0
0 0 0 1 0 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0
...