#include <stdio.h>
#define MAX_ROW 12
typedef struct Tag_Stack
{
int i;
int j;
}V_Stack;
static V_Stack g_Stack[MAX_ROW];
static int g_StackNum;
static int g_Stack_j;
static unsigned char UseFlag[MAX_ROW][MAX_ROW] = {0};
static void SetUseFlag(int i, int j)
{
UseFlag[i][j] = 1;
}
static void ClearUseFlag(int i, int j)
{
UseFlag[i][j] = 0;
}
static void PushStack(int i, int j)
{
if(g_Stack_j >= MAX_ROW)
{
return;
}
g_Stack[g_Stack_j].i = i;
g_Stack[g_Stack_j].j = j;
++g_Stack_j;
}
static void PopStack()
{
--g_Stack_j;
}
static void ClearStack()
{
}
static int IsValid(int row, int col)
{
int i = 0, j = 0, m = 0, n = 0;
for(i=0;i<row;i++)
{
for(j=0;j<MAX_ROW;j++)
{
if(UseFlag[i][j])
{
if(i == row)
return 0;// 同一行无效
else if(j == col)
return 0;// 同一列无效
else
{
m = i;
n = j;
while(m<MAX_ROW && n<MAX_ROW)
{
m+=1;
n+=1;
if(m==row && n==col)
{
return 0;
}
}
m = i;
n = j;
while(m<MAX_ROW && n>=0)
{
m+=1;
n-=1;
if(m==row && n==col)
{
return 0;
}
}
}
}
}
}
return 1;
}
void FindValid(int i)
{
int j = 0, ValidFlag = 0;
int save = 0;
if(i < MAX_ROW)
{
for(j=0;j<MAX_ROW;j++)
{
if(IsValid(i,j))
{
//printf("valid:%d,%d\n",i,j);
PushStack(i,j);
save = g_Stack_j;
SetUseFlag(i,j);
FindValid(i+1);
ClearUseFlag(i,j);
ValidFlag = 1;
if(save == g_Stack_j)
{
PopStack();
}
}
}
}
else
{
#if 0 //print result
for(i=0;i<MAX_ROW;i++)
{
printf("%d,%d\t", g_Stack[i].i, g_Stack[i].j);
}
printf("\n");
#endif
++g_StackNum;
}
}
void main()
{
int i = 0, j = 0;
FindValid(0);
printf("g_StackNum:%d\n",g_StackNum);
}
/*
MAX_ROW:g_StackNum
8:92
9:352
10:724
11:2680
12:14200
*/
8皇后问题---好久没做这个了。练练手。
最新推荐文章于 2023-10-04 14:31:53 发布