#define COLS 10
#define WAYS 100
int col[COLS];
int result[WAYS][COLS];
bool isVaild(int level) {
for (int i = 1; i < level; ++i) {
if (col[i] == col[level] || abs(i - level) == abs(col[i] - col[level]))
return false;
}
return true;
}
int eightQueen() {
memset(col, 0, sizeof(int) * COLS);
memset(result, 0, sizeof(int) * COLS * WAYS);
int level = 1;
col[level] = 0;
int count = 0;
while (level >= 1) {
col[level]++;
while (col[level] <= 8 && !isVaild(level)) {
col[level]++;
}
if (col[level] <= 8) {
if (level == 8) {
for (int i = 1; i <= 8; ++i) {
result[count][i] = col[i];
}
count++;
} else {
level++;
col[level] = 0;
}
} else {
level--;
}
}
return count;
}
写程序输出8皇后问题的所有排列,要求使用非递归的深度优先遍历。
最新推荐文章于 2023-08-20 09:55:43 发布