最近我正在尝试解决著名的小主教算法问题。在我读到的一个网站中,我应该将棋盘分成黑白部分以优化执行。之后,我应该使用回溯来计算将主教分别放在黑色方块和白色方块上的可能方法的数量。
在下面的代码中,我尝试仅将 6 个主教放在 8 x 8 棋盘的白色方格上。我这样做只是为了验证该技术是否真的有效。
//inside main function
int k = 6; //number of bishops
int n = 8; //length of one side of chessboard
Integer[] positions = new Integer[k];
long result = backtrack(positions, 0, n);
//find how many times we double counting each possible combination of bishops
int factor = 1;
for(int i = k; i>0; i--) {
factor = factor * i;
}
System.out.println("The result is " + result/factor);
//implementation of other functions
public long backtrack(Integer[] prevPositions, int k, int n) {
if(k == 6) {
return 1;
}
long sum = 0;
Integer[] candidates = new Integer[n*n];
int length = getCandidates(prevPositions, k, candidates, n);
for(int i=0 ; i<length ; i++) {
prevPositions[k] = candidates[i];
sum += backtrack(prevPositions,k+1,n);
}
return sum;
}
public Integer getCandidates(Integer[] prevPositions, int k, Integer[] candidates, int n) {
int length = 0;
//only white squares are considered as candidates, hence i+=2
for (int i = 0; i < n*n; i+=2) {
boolean isGood = true;
int iRow = i / n;
int iCol = i % n;
for (int j = 0; j < k; j++) {
int prev = prevPositions[j];
if (i == prev) {
isGood = false;
break;
} else {
int prevRow = prev / n;
int prevCol = prev % n;
if (Math.abs(iRow - prevRow) == Math.abs(iCol - prevCol)) {
isGood = false;
break;
}
}
}
if(isGood) {
candidates[length] = new Integer(i);
length++;
}
}
return length;
}
尽管我可以理解为什么将棋盘划分为白色和黑色方块可以优化问题,但仍然需要大约 11 秒来计算将所有主教只放在白色方块上的可能方法的数量。你能帮我吗?我究竟做错了什么?