八皇后问题
# include <stdio.h> # include <memory.h> # include <stdbool.h> int count = 0; bool is_safe(int row, int col, int chessp[][8]) { int i, j; /*判断列*/ for(j = 0; j < row; ++j) { if (chessp[j][col]) { return false; } } /*判断左上*/ for (i = row-1, j = col-1; i >= 0 && j >=0; --i, --j) { if(chessp[i][j]) { return false; } } /*判断右上*/ for(i = row-1, j = col+1; i >= 0 && j < 8; --i, ++j) { if(chessp[i][j]) { return false; } } return true; } void queen(int row, int col, int chessf[][8]) { int i, j; /*结束条件*/ if (row == 8) { count++; printf("第%d种:\n", count); for(i = 0; i < 8; ++i) { for(j = 0; j < 8; ++j) { printf("%d ", chessf[i][j]); } printf("\n"); } printf("\n\n"); return; } else { for(i = 0; i < col; ++i) { if(is_safe(row, i, chessf)) { chessf[row][i] = 1; queen(row+1, col, chessf); //递归 chessf[row][i] = 0; //回溯 } } } } int main(void) { int chess[8][8]; memset(chess, 0, sizeof(chess)); //开始状态,棋盘置空 queen(0, 8, chess); return 0; }