首页 > 代码库 > 四皇后问题
四皇后问题
递归
#include <stdio.h>#include <stdlib.h>#include <errno.h>#define NUM 4int total = 0;void print_board(int *board){ printf("\n"); for (int i = 0; i < NUM; i++) { for (int j = 0; j < NUM; j++) { printf("%4d", board[j] == i ? 1 : 0); } printf("\n"); }}int check(int *board, int col){ for (int i = 0; i < col; i++) { if (board[i] == board[col] || abs(board[i] - board[col]) == abs(i - col)) { return 0; } } return 1;}void queen(int *board, int col){ if (col == NUM) { print_board(board); total++; return; } for (int row = 0; row < NUM; row++) { board[col] = row; if (check(board, col)) { queen(board, col + 1); } }}int main(int argc, char **argv){ printf("total = %d\n", total); int board[NUM]; for (int i = 0; i < NUM; i++) { board[i] = 0; } queen(board, 0); printf("total = %d\n", total); getchar(); return 0;}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。