高手帮我解解,谢谢!!!
你是新手吗?
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 30
#define MARK 'Q'
void initial(void);
void display(void);
void class_1(void);
void class_2(void);
void class_3(void);
void class_4(void);
int n;
char board[MAXSIZE+1][MAXSIZE+1];
void main(void)
{
void (*funct[])() = { class_1, class_2,
class_4, class_3,
class_1, class_2
};
char line[100];
printf("\nOne Solution for N Queens' Problem");
printf("\n==================================");
printf("\n\nBoard Size Please (N > 3) --> ");
gets(line);
n = atoi(line);
if (n > 3) {
initial();
(*funct[n % 6])();
display();
}
else
printf("\nIllegal Board Size.");
}
void initial(void)
{
int i, j;
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
board[i][j] = ' ';
}
#define DRAWGRID (N) { inti;
printf("\n+");
for (i = 1; i <= N; i++) printf("-+"); }
#define DRAWLINE(N, r) { int i; printf("\n|"); for (i = 1; i <= N; i++) printf("%c|", board[r][i]); }
void display(void)
{
int r;
DRAWGRID(n);
for (r = 1; r <= n; r++) {
DRAWLINE(n, r);
DRAWGRID(n);
}
printf("\n");
}
void class_1(void)
{
int i;
for (i = 1; i <= n/2; i++)
board[2*i][i] = board[2*i-1][n/2+i] = MARK;
}
void class_2(void)
{
int i;
for (i = 1; i <= (n-1)/2; i++)
board[2*i][i] = MARK;
for (i = 1; i <= (n+1)/2; i++)
board[2*i-1][(n-1)/2+i] = MARK;
}
void class_3(void)
{
int i;
for (i = 1; i <= (n-3)/2; i++)
board[2*i+2][i] = board[2*i+3][(n-1)/2+i] = MARK;
board[1][n-1] = board[2][(n-2)/2] = board[3][n] = MARK;
}
void class_4(void)
{
int i;
if (n > 8) {
for (i = 1; i <= 3; i++)
board[2*i-1][n/2-2+i] = MARK;
board[2][n] = board[4][1] = board[6][n-1] = MARK;
for (i = 1; i <= n/2 - 3; i++)
board[2*i+5][i+1] = board[2*i+6][n/2+1+i] = MARK;
}
else {
for (i = 1; i <= 4; i++)
board[2*i][i] = MARK;
board[1][6] = board[3][5] = MARK;
board[5][8] = board[7][7] = MARK;
}
}
/*C写的.回朔法*/
#include<stdio.h>
#define N 20
int x[N] ; //当前解
int sum = 0 ; //可行解的数量
int n=8 ; //规模
bool Place( int k )
{
int i;
for( i = 1 ; i < k ; i++ )
{
if(abs(k-i)==abs(x[k]-x[i])||x[i]==x[k])
{
return false;
}
}
return true;
}
void Backtrack( int t )
{
if( t > n)
{
sum++;
for(int i=1;i<=n;i++)
{
/* for(int j=1;j<=n;j++)
{
if(j==x[i])
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
*/
printf("%-3d%-3d\n",i,x[i]);
}
printf("\n");
}
else
{
for( int i = 1 ; i<= n ; i++ )
{
x[t] = i ;
if( Place( t )==true )
{
Backtrack( t + 1 ) ;
}
}
}
}
int main()
{
int i;
scanf("%d",&n);
for( i = 1 ; i <= n ; i++ )
{
x[i] = 0 ;
}
Backtrack( 1 ) ;
printf("%d\n",sum);
}