我正在尝试为8 queens puzzle开发一个解决方案,其中8个皇后应放在8x8棋盘上,这样就不会有两个可以相互攻击。我能够打印出我的'#'板,但无法弄清楚如何在第一个位置放置一个女王,并将所有水平,垂直和对角线点都设为'x'。
这是我到目前为止所做的:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define ROW 8
#define COL 8
// Make the chessboard
int main(int argc, char * argv[])
{
char board[ROW][COL];
int i, j;
for(i = 0; i < ROW; i++)
{
for(j = 0; j < COL; j++)
{
board[i][j] = '#';
printf(" %c", board[i][j]);
}
printf("\n");
}
return 0;
}
// Place queen on first '#'
int placeQueen(char board[ROW][COL])
{
char queenSpace;
int i, j;
for(i = 0; i < ROW; i++)
{
for(j = 0; j < COL; j++)
{
queenSpace = 'Q';
board[i][j] = queenSpace;
printf(" %c", board[1][1]);
}
printf("\n");
}
return 0;
}
现在输出在左边,我需要它如右图所示:
# # # # # # # # Q x x x x x x x
# # # # # # # # x x # # # # # #
# # # # # # # # x # x # # # # #
# # # # # # # # x # # x # # # #
# # # # # # # # x # # # x # # #
# # # # # # # # x # # # # x # #
# # # # # # # # x # # # # # x #
# # # # # # # # x # # # # # # x
这是我的算法:
我从未使用过2d数组做任何工作或程序,所以我们非常感谢任何帮助甚至示例代码!
答案 0 :(得分:1)
一些提示。摘要您的主要数据类型:
#define ROW 8
#define COL 8
typedef char t_board[ROW][COL];
#define ItRows(Var) for (int Var = 0; Var < ROW; Var++)
#define ItCols(Var) for (int Var = 0; Var < COL; Var++)
#define EMPTY '+'
#define QUEEN 'Q'
#define ATTACK '-'
#define bool int
#define true 1
#define false 0
然后你可以简化在数据类型上完成的操作声明,并专注于单个步骤的逻辑:
void init(t_board board) {
ItRows(r)
ItCols(c)
board[r][c] = EMPTY;
}
void show(t_board board) {
ItRows(r) {
ItCols(c)
printf(" %c", board[r][c]);
printf("\n");
}
}
void assign(t_board target, const t_board source) {
ItRows(r)
ItCols(c)
target[r][c] = source[r][c];
}
bool reserve(t_board board, int row, int col, char cell) {
if (board[row][col] == QUEEN)
return false;
board[row][col] = cell;
return true;
}
bool place_queen(t_board board, int row, int col) {
ItRows(r)
if (r != row && !reserve(board, r, col, ATTACK))
return false;
ItCols(c)
if (c != col && !reserve(board, row, c, ATTACK))
return false;
#define AttackDiag(R, C) \
for (int r = row + R, c = col + C; r >= 0 && c >= 0 && r < ROW && c < COL; r += R, c += C) \
if (!reserve(board, r, c, ATTACK)) \
return false;
AttackDiag(+1, +1)
AttackDiag(+1, -1)
AttackDiag(-1, +1)
AttackDiag(-1, -1)
return reserve(board, row, col, QUEEN);
}
int main_queens(int argc, char **argv) {
t_board b;
init(b);
assert(place_queen(b, 3, 2));
show(b);
return 0;
}