#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TREE_SIZE 100
#define OVERFLOW -1
#define OK 1
#define ERROR -1
#define TRUE 1
#define FALSE 0
typedef int Status;
//八皇后问题,不能位于同一行同一列或者同一对角线
#define AMOUNT 8
typedef int** ChessType;
Status Judge(int** chess, int i, int j)
{
for (int p = 1; p < j; p++)
if (chess[i][p] == 1)
return FALSE;
for (int p = 1; p < i; p++)
if (chess[p][j] == 1)
return FALSE;
int row = i - 1, col = j - 1;
while (row >= 1 && col >= 1)
{
if (chess[row][col] == 1)
return FALSE;
row--;
col--;
}
row = i - 1, col = j + 1;
while (row >= 1 && col <= AMOUNT)
{
if (chess[row][col] == 1)
return FALSE;
row--;
col++;
}
return TRUE;
}
void PrintChess(int** chess, int n, int* count)
{
printf("第%d种棋盘情况\n", *count);
printf("\t");
for (int i = 1; i <= n; i++)
printf("%d\t", i);
printf("\n\n");
for (int i = 1; i <= n; i++)
{
printf("%d\t", i);
for (int j = 1; j <= n; j++)
{
if (chess[i][j] == 1)
printf("□\t");
else
printf(".\t");
}
printf("\n\n\n");
}
}
void Trial(ChessType chess, int i, int n, int* count)
{
if (i > n)
{
PrintChess(chess, n, count);
(*count)++;
}
else
{
for (int j = 1; j <= n; j++)
{
if (Judge(chess, i, j))
{
chess[i][j] = 1;
Trial(chess, i + 1, n, count);
}
chess[i][j] = 0;
}
}
}
主函数:
int main()
{
ChessType chess;
chess = (ChessType)malloc(sizeof(int*) * (AMOUNT + 1));
if (!chess) exit(OVERFLOW);
for (int i = 1; i <= AMOUNT; i++)
{
chess[i] = (int*)malloc(sizeof(int) * (AMOUNT + 1));
if (!chess[i]) exit(OVERFLOW);
for (int j = 1; j <= AMOUNT; j++)
chess[i][j] = 0;
}
int count = 1;
Trial(chess, 1, AMOUNT, &count);
getchar();
return 0;
}
结果: