将两个程序整合成一个程序,第二个程序输出的Q显示的是第一程序输出的数字
#include<stdio.h>#define NUM 8
int a[NUM+1];
int main()
{
int i,k,flag,not_finish=1,count=0;
i=1;
a[1]=1;
printf("The possible configuration of 8 queens are: /n");
while(not_finish) /*not_finish=1:
{
while(not_finish&&i<=NUM)
{
for(flag=1,k=1;flag&&k<i;k++)
if(a[k]==a[i])flag=0;
for(k=1;flag&&k<i;k++)
if((a[i]==a[k]-(k-i))||(a[i]==a[k]+(k-i))) flag=0;
if(!flag)
{
if(a[i]==a[i-1])
{
i--;
if(i>1&&a[i]==NUM)
a[i]=1;
else if(i==1&&a[i]==NUM)
not_finish=0;
else a[i]++;
}
else if(a[i]==NUM) a[i]=1;
else a[i]++;
}
else if(++i<=NUM)
if(a[i-1]==NUM) a[i]=1;
else a[i]=a[i-1]+1;
}
if(not_finish)
{
++count;
printf((count-1)%3?"\n"" [%2d]: ":"\n"" [%2d]: ",count);
for(k=1;k<=NUM;k++)
printf(" %d ",a[k]);
if(a[NUM-1]<NUM) a[NUM-1]++;
else a[NUM-1]=1;
i=NUM-1;
}
}
}
#include <stdio.h>
#include <stdlib.h>
#define N 8
int column[N+1];
int rup[2*N+1];
int lup[2*N+1];
int queen[N+1] = {0};
int num;
void backtrack(int);
int main(void) {
int i;
num = 0;
for(i = 1; i <= N; i++)
column[i] = 1;
for(i = 1; i <= 2*N; i++)
rup[i] = lup[i] = 1;
backtrack(1);
return 0;
}
void showAnswer() {
int x, y;
printf("\n解答 %d\n", ++num);
for(y = 1; y <= N; y++) {
for(x = 1; x <= N; x++) {
if(queen[y] == x) {
printf(" Q");
}
else {
printf(" .");
}
}
printf("\n");
}}
void backtrack(int i) {
int j;
if(i > N) {
showAnswer();
}
else {
for(j = 1; j <= N; j++) {
if(column[j] == 1 && rup[i+j] == 1 && lup[i-j+N] == 1) {
queen[i] = j;
column[j] = rup[i+j] = lup[i-j+N] = 0;
backtrack(i+1);
column[j] = rup[i+j] = lup[i-j+N] = 1;
}
}
}
}