我该如何实现八皇后问题?我应该使用深度优先搜索(DFS)还是广度优先搜索(BFS),我认为DFS会更好。有人能给一些伪代码/指导吗?
|i-k|=|j-l|(对角线),| | 表示绝对值
bool place(k,i)
{
//如果皇后可以放在第k行和第i列,则返回true
//x[]是一个全局数组,前(k-1)个值已经设置好了。
//x[p]=q表示皇后位于位置(p,q)
for(j=1 to k-1)
{
if(x[j]==i)||(ABS(x[j]-i)==ABS(j-k)) //检查是否有另一个皇后在同一列或对角线上
return false;
}
return true;
}
使用回溯打印所有可能的摆法:
void NQueens(k,n) {
for(i=1 to n)
{
if(place(k,i)) //检查皇后是否可以放在(k,i)处
{
x[k]=i;
if(k==n) then write (x[1:n]);
else Nqueens(k+1,n);
}
}
}
*参考自Saurabh学校
package com.org.ds.problems;
public class NQueueProblem {
private static int totalSolution = 0;
public static void main(String[] args) {
int n = 5;
int arr[][] = new int[n][n];
backTrack(arr, 0);
System.out.println("\nTotal Number of Solutions are:- " + totalSolution);
}
private static void printQueuens(int[][] arr) {
totalSolution++;
System.out.println("\n========Start Printing Solution "+totalSolution+"=========");
for(int i=0; i<arr.length;i++) {
for(int j=0; j<arr.length;j++) {
if(arr[i][j] == 1)
System.out.print(" Q"+(i+1) + " |");
else
System.out.print(" |");
}
System.out.println();
}
}
private static boolean backTrack(int[][] arr, int row) {
if (row < 0 || row >= arr.length)
return true;
for (int col = 0; col < arr.length; col++) {
if (isAttacked(arr, row, col)) {
arr[row][col] = 1;
if (backTrack(arr, row + 1)) {
if(row == (arr.length-1)) {
printQueuens(arr);
arr[row][col] = 0;
}
else {
return true;
}
} else {
arr[row][col] = 0;
}
}
}
return false;
}
private static boolean isAttacked(int[][] arr, int row, int col) {
if (row == 0)
return true;
// check for same row
for (int i = 0; i < arr.length; i++) {
if (arr[row][i] == 1)
return false;
}
// check for same col
for (int i = 0; i <= row; i++) {
if (arr[i][col] == 1)
return false;
}
// check for diagonal
// a.) Left dia
int i = row - 1;
int j = col - 1;
while (i >= 0 && j >= 0) {
if (arr[i][j] == 1)
return false;
i--;
j--;
}
// b.) right dia
i = row - 1;
j = col + 1;
while (i >= 0 && j < arr.length) {
if (arr[i][j] == 1)
return false;
i--;
j++;
}
return true;
}
}