作者dh3014 (普物期末大作战)
看板ck54th309
标题Re: 呼叫肇强 求救求救
时间Sun Nov 10 13:40:22 2002
※ 引述《yhsw (看着海而犹豫)》之铭言:
: 我八皇后根本不会写
: 因为阵列还没看完
: 我是要写出所有的解
: 帮我一下八
: 花你一点点时间
: 假如能帮我写一下的话
: [email protected]
: 这是我的信箱
: 拜托拜托了
#include <iostream.h>
/* this program solves $BOARDWIDTH-queen problem */
const int BOARDWIDTH = 8;
int solution_count;
void recursion (int, bool *, bool *, bool *, int *);
void main (void) {
/* record row[i], left_diagonal[j], right_diagonal[k] is occupied or not */
bool row[BOARDWIDTH] = {false};
bool left_diagonal[BOARDWIDTH * 2 - 1] = {false};
bool right_diagonal[BOARDWIDTH * 2 - 1] = {false};
/* record the position of every queen */
int position[BOARDWIDTH];
recursion (0, row, left_diagonal, right_diagonal, position);
cout << "Total solution: " << solution_count << endl;
}
void printBoard (int *);
void recursion (int depth, bool * row, bool * diagonal,
bool * counter_diagonal, int * pos) {
if (depth == BOARDWIDTH)
printBoard (pos);
else
for (int i = 0; i < BOARDWIDTH; ++i)
if (!row[i] && !diagonal[i + depth] &&
!counter_diagonal[BOARDWIDTH - i + depth - 1]) {
row[i] = diagonal[i + depth] =
counter_diagonal[BOARDWIDTH - i + depth - 1] = true;
pos[depth] = i;
recursion (depth + 1, row, diagonal, counter_diagonal, pos);
row[i] = diagonal[i + depth] =
counter_diagonal[BOARDWIDTH - i + depth - 1] = false;
}
}
void printBoard (int * pos) {
for (int i = 0; i < BOARDWIDTH; ++i)
for (int j = 0; j < BOARDWIDTH; ++j)
cout << (j == pos[i] ? 1 : 0) <<
(j == BOARDWIDTH - 1 ? '\n' : ' '); cout << endl;
++solution_count;
}
--
※ 发信站: 批踢踢实业坊(ptt.csie.ntu.edu.tw)
◆ From: 140.112.249.198
1F:→ Rayblade:小无说她看不懂 推 61.217.56.226 11/10