1.利用回溯算法求解八皇后问题
//用来记录各个棋子的位置,下标表示行,元素值代表列
int [] result = new int[8];
//依次存放每个行
public void cal8queues(int row){
if(row == 8){
printqueens(result);
// 由于是递归的解法,所以每找到一种解法,就需要返回
return;
}
//依次遍历每一列,看看那一列是合法的
for(int column = 0; column < 8; column++){
if(isOK(row,column)){
result[row] = column;
cal8queues(row + 1);
}
}
}
//判断某一行中的棋子应该放在哪一列
public boolean isOK(int row, int column){
int leftup = column - 1;
int rightup = column + 1;
for(int i = row - 1; i >=0; i--){
if(result[i] == column) return false;
if(leftup >= 0){
if(result[i] == leftup) return false;
}
if(rightup < 8){
if(result[i] == rightup) return false;
}
// 当不断地向上面更小地行检索时,应当变更 left,right 的大小
leftup--;
rightup++;
}
return true;
}
//打印出合法的位置
public void printqueens(int [] result) {
for (int row = 0; row < 8; row++) {
for (int column = 0; column < 8; column++) {
if (result[row] == column) System.out.print("Q" + " ");
else System.out.print("*" + " ");
}
System.out.println();
}
System.out.println();
}
2.利用回溯算法求解 0-1 背包问题
public int maxW = Integer.MIN_VALUE;
public void f(int i, int cw, int[] items, int n, int w){
if (cw == w || i == n) {
if (cw > maxW) maxW = cw;
return;
}
f(i+1, cw, items, n, w);
if (cw + items[i] <= w) {
f(i+1,cw + items[i], items, n, w);
}
}