已经写完代码并通过编译了,但是无法运行,可是我检查了一个晚上还是找不出来哪里有错。。能帮我看看吗?我觉得可能出错在find函数和size函数那里。万分感谢!核心代码是借鉴书上的(邓俊辉数据结构C++),应该没有问题吧......
#include <iostream>
using namespace std;
class queen{
public:
int x, y;
queen(int xx = 0, int yy = 0) :x(xx), y(yy) {}
};
class SqStack{
private:
enum{MaxSize=100};
queen data[MaxSize];
int top;
public:
SqStack();
int size();
queen pop();
int find(queen q);
void push(queen q);
};
SqStack::SqStack(){
top=-1;
}
int SqStack::size(){ //栈里面的皇后的个数
int i=top;
i++;
return i;
}
queen SqStack::pop(){
if(top==-1)
throw "溢出";
else
return data[top];
top--;
}
int SqStack::find(queen q){ //查找是否与之前的皇后冲突
int i;
int s=-1;
for (i=top;i>=0;i--) {
if (q.y==data[i].y||(q.x+q.y==data[i].x+data[i].y)||(q.x-q.y==data[i].x-data[i].y)){
s++;
break;
}
}
return s;
}
void SqStack::push(queen q){
if(top==MaxSize-1)
throw "上溢";
else{
++top;
data[top]=q;
}
}
void placeQueens(int N) {
SqStack solu;
queen q(0, 0);
int nCheck=0;
int nSolu=0;
do { //反复试探、回溯
if (solu.size()>=N || q.y>=N) { //若已出界,则
q = solu.pop(); q.y++;} //回溯一行,并继续试探下一列
else { //否则,试探下一行
while ((q.y < N) && (0 <= solu.find(q))) //通过与已有皇后的比对
{ q.y++; nCheck++; }//尝试找到可摆放下一皇后的列
if (N > q.y) { //若存在可摆放的列,则
solu.push(q); //摆上当前皇后,并
if (N <= solu.size()) nSolu++; //若部分解已成为全局解,则通过全局变量nSolu计数
q.x++; q.y = 0;
} //转入下一行,从第0列开始,试探下一皁后
}
} while ((0 < q.x) || (q.y < N));
cout<<"结果"<<endl;
cout<<nCheck<<" "<<nSolu;
}
int main(int argc, char** argv) {
placeQueens(4);
return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话: