八皇后 循环实现
程序代码:
#include <stdio.h> #define N 8 char board2[N + 2][N + 2]; int QueenPos2[N]; int count2 = 0; //定义一个方向的结构体 typedef struct _Tag_Pos { int xpos; int ypos; }Pos2; Pos2 pos2[3] = { { -1, -1 }, { -1, 0 }, { -1, 1 } }; void init2(void); void display2(void); int check2(int x, int y); void find2(void); int main(int argc, char *argv[]) { init2(); find2(); return 0; } //初始化 void init2(void) { for (int i = 0; i < N;i++) { QueenPos2[i] = 1; } for (int i = 0; i < N + 2; i++) { for (int j = 0; j < N + 2; j++) { if ((i == 0) || (i == N + 1)) { board2[i][j] = '#'; } else if ((j == 0) || (j == N + 1)) { board2[i][j] = '#'; } else { board2[i][j] = ' '; } } } } //输出 void display2(void) { for (int i = 0; i < N + 2; i++) { for (int j = 0; j < N + 2; j++) { printf("%c", board2[i][j]); } printf("\n"); } } //检测某个位置是不是可以放置皇后 int check2(int i, int j) { int ret = 1; for (int p = 0; p < 3; p++) { int ni = i; int nj = j; while (ret && (board2[ni][nj] != '#')) { ni = ni + pos2[p].xpos; nj = nj + pos2[p].ypos; ret = ret && (board2[ni][nj] != '*'); } } return ret; } //找出所有的皇后 void find2(void) { //行 for (int i = 1; i <= N;) { int flag = 1; for (int j = QueenPos2[i]; j <= N;j++) { //检测一下可不可以安置一个皇后 if (check2(i,j)) { QueenPos2[i] = j; board2[i][j] = '*'; flag = 0; break; } } //如果flag==1?表示没找到,否则找到 if (flag) { i--; board2[i][QueenPos2[i]] = ' '; QueenPos2[i]++; } else { i++; } getchar(); } display2(); }
帮忙看一下怎么回事啊,我没有使用递归来实现,使用了循环来实现,但是就是得不到结果