-
Notifications
You must be signed in to change notification settings - Fork 103
/
eightQueen.c
78 lines (74 loc) · 1.36 KB
/
eightQueen.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <stdio.h>
//八皇后问题,这边用了两种方法,simp的比较简单,本质上是一样的
int isSafe(int *a, int index)
{
int i;
for (i = 0; i < index; i++)
{
if (a[i] == a[index])
return 0;
if (index - a[index] == i - a[i] || index + a[index] == i + a[i])
return 0;
}
return 1;
}
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
int QueenDo(int *a, int start, int n)
{
int i, j;
int count = 0;
if (start >= n)
{
for (j = 0; j < n; j++)
printf("%d ", a[j]);
printf("\n");
return 1;
}
for (i = start; i < n; i++)
{
swap(a+start, a+i);
if (!isSafe(a, start))
{
swap(a+start, a+i);
continue;
}
count = count + QueenDo(a, start+1, n);
swap(a+start, a+i);
}
return count;
}
int eightQueen(int n)
{
int a[100];
int i;
for (i = 0; i < n; i++)
{
a[i] = i;
}
//return QueenDo(a, 0, n);
return simp(a, 0, n);
}
int simp(int *a, int index, int n)
{
int i;
static int count = 0;
if (index >= n)
{
count++;
} else
{
for (i = 0; i < n; i++)
{
a[index] = i;
if (!isSafe(a, index))
continue;
simp(a, index+1, n);
}
}
return count;
}