-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathEightQueenUsingStack.cpp
More file actions
124 lines (107 loc) · 1.73 KB
/
EightQueenUsingStack.cpp
File metadata and controls
124 lines (107 loc) · 1.73 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include <stdio.h>
#include <math.h>
#include <stack>
using namespace std;
/*八皇后问题是在8*8的棋盘上放置8枚皇后,使得棋盘中每个横向、纵向、左上至右下斜向、右上至左下斜向均只有一枚皇后*/
const int N = 8; //棋盘行数
int a[N] = {0}; //表示棋盘,若a[2]=2,则表示在第3行第2列放一个皇后,因为同一行不能放两个皇后,所以只需要1维数组就可以表示一个棋盘。
int solution = 0;//解的个数
struct Node
{
int row;
int col;
};
//row行,col列, 是否可以摆皇后
bool IsOK(Node node)
{
for (int i = 0; i < node.row; i++)
{
if (a[i] == node.col || (abs(a[i] - node.col) == node.row - i))
{
return false;
}
}
return true;
}
//打印出所有解
void Print()
{
printf("第%d种解:\n", ++solution);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (a[i] == j)
{
printf("%d", i);
}
else
{
printf("#");
}
}
printf("\n");
}
printf("-----------------\n");
}
void DSF()
{
Node node;
stack<Node> stack;
node.row = 0;
node.col = 0;
stack.push(node);
while(stack.size() >= 1)
{
//--find
node = stack.top();
while (node.col < N && !IsOK(node))
{
node.col++;
}
if (node.col < N)
{
//--forward
if (node.row < N-1)
{
//把ok的节点放到当前层
a[node.row] = node.col;
stack.pop();
stack.push(node);
//进入下一层的第一个节点
node.row++;
node.col = 0;
stack.push(node);
}
else
{
//--done
a[node.row] = node.col;
Print();
//进入当前层的下一个结点
//node = stack.top();
node.col++;
stack.pop();
stack.push(node);
}
}
else
{
//--back
stack.pop();
if (stack.size() == 0)
{
return;
}
node = stack.top();
node.col++;
stack.pop();
stack.push(node);
}
}
}
int main()
{
DSF();
return 0;
}