求教:写八皇后时遇到的奇葩问题!
第一次我让整形变量num作为计数器,结果让我费解;第二次我让answer[0].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;
}这是上面代码的运行截图,没有问题 92个结果
[local]1[/local]
注意下面我把计数器换成了num
程序代码:#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;
}结果竟然是这样






