八皇后问题的后续更新

在一个c文件中实现八皇后的问题

#include<stdio.h>
#define EIGENT 8

bool isSafe(int (*chessboard)[EIGENT],const int row, const int col);
void orderQueen(int(*chessboard)[EIGENT],const int row);
void drawChessboard(int(*chessboard)[EIGENT]);

bool isSafe(int (*chessboard)[EIGENT],const int row, const int col){
    int i;
    int j;
    
    for(i = row -1,j = col - 1;i >= 0 && j >= 0;i--,j--){
        if(chessboard[i][j] == 1){
            return false;
        }
    }
    for(i = row - 1,j = col;i >= 0;i--){
        if(chessboard[i][j] == 1){
            return false;
       }
   }
  for(i = row - 1,j = col + 1;i >= 0 && j < EIGENT; i-- , j++){
          if(chessboard[i][j] == 1){
            return false;
          }
  }
  return true;
}

void orderQueen(int(*chessboard)[EIGENT],const int row){
    static int count = 0;
    if(row >= EIGENT){
        ++count;
        drawChessboard(chessboard);
    }else{
        int col;

        for(col = 0; count < 23  && col < EIGENT;col++){           //输出23种结果!

            chessboard[row][col] = 1;
            if(isSafe(chessboard,row,col)){
                orderQueen(chessboard,row + 1);
            }
            chessboard[row][col] = 0;
        }
    }
}

void drawChessboard(int(*chessboard)[EIGENT]){
    int row;
    int col;
    
    static int count = 0;
    
    printf("第%d个解:\n",++count);
    for(row = 0; row < EIGENT; row++) {
        for(col = 0; col < EIGENT; col++) {
            printf("%2d", chessboard[row][col]);
        }
        printf("\n");
    }
}

int main(){
    int chess[EIGENT][EIGENT] = {0};
    orderQueen(chess,0);
    return 0;
}
posted @ 2018-05-28 20:32  离愁i  阅读(104)  评论(0编辑  收藏  举报