求教:写八皇后时遇到的奇葩问题
不知道为啥截不了图了。只能上代码了。程序代码:
#include<stdio.h> #define N 8 typedef struct { int n; int row; int line; }AnswerType; AnswerType answer[N]; typedef enum { notoccued = 0, occued = 1 }Ifoccued; Ifoccued RowOccued[N]; Ifoccued LeftTop_RightDown[2*N-1]; Ifoccued LeftDown_RightTop[2*N-1]; void print(); int num; void start(int LineIndex) { for(int RowIndex=0;RowIndex<8;RowIndex++) { if(RowOccued[RowIndex]==notoccued&&LeftTop_RightDown[RowIndex-LineIndex+N-1]==notoccued &&LeftDown_RightTop[RowIndex+LineIndex]==notoccued) { RowOccued[RowIndex]=occued; LeftTop_RightDown[RowIndex-LineIndex+N-1]=occued; LeftDown_RightTop[RowIndex+LineIndex]=occued; answer[LineIndex].row=RowIndex; answer[LineIndex].line=LineIndex; if(LineIndex==7) { num++; answer[0].n++; print(); RowOccued[N]=notoccued; LeftTop_RightDown[2*N-1]=notoccued; LeftDown_RightTop[2*N-1]=notoccued; }else { start(LineIndex+1); } RowOccued[RowIndex]=notoccued; LeftTop_RightDown[RowIndex-LineIndex+N-1]=notoccued; LeftDown_RightTop[RowIndex+LineIndex]=notoccued; } } } void print() { printf("第%d个结果为:",num); for(int i=0;i<N;i++) { printf("[%d,%d] ",answer[i].line+1,answer[i].row+1); } printf("\n"); } int main() { num=0; answer[0].n=0; start(0); return 0; }
注意倒数第14行的printf("第%d个结果为:",num); 根据我的设想应该是输出第1个结果为...一直到输出第92个结果为
但实际是输出了92个第一个结果为
然后我将整形计数器num换成了answer结构体中的变量n,代码如下
程序代码:
#include<stdio.h> #define N 8 typedef struct { int n; int row; int line; }AnswerType; AnswerType answer[N]; typedef enum { notoccued = 0, occued = 1 }Ifoccued; Ifoccued RowOccued[N]; Ifoccued LeftTop_RightDown[2*N-1]; Ifoccued LeftDown_RightTop[2*N-1]; void print(); int num; void start(int LineIndex) { for(int RowIndex=0;RowIndex<8;RowIndex++) { if(RowOccued[RowIndex]==notoccued&&LeftTop_RightDown[RowIndex-LineIndex+N-1]==notoccued &&LeftDown_RightTop[RowIndex+LineIndex]==notoccued) { RowOccued[RowIndex]=occued; LeftTop_RightDown[RowIndex-LineIndex+N-1]=occued; LeftDown_RightTop[RowIndex+LineIndex]=occued; answer[LineIndex].row=RowIndex; answer[LineIndex].line=LineIndex; if(LineIndex==7) { num++; answer[0].n++; print(); RowOccued[N]=notoccued; LeftTop_RightDown[2*N-1]=notoccued; LeftDown_RightTop[2*N-1]=notoccued; }else { start(LineIndex+1); } RowOccued[RowIndex]=notoccued; LeftTop_RightDown[RowIndex-LineIndex+N-1]=notoccued; LeftDown_RightTop[RowIndex+LineIndex]=notoccued; } } } void print() { printf("第%d个结果为:",answer[0].n); for(int i=0;i<N;i++) { printf("[%d,%d] ",answer[i].line+1,answer[i].row+1); } printf("\n"); } int main() { num=0; answer[0].n=0; start(0); return 0; }
与第一段代码唯一不同之处就是把倒数第14行改成printf("第%d个结果为:",answer[0].n);
输出就对了 是从1到92
我不明白为什么第一段代码结果输出的全是1
求解!谢谢!