请问怎样出结果(N皇后问题)

qq_45964723 2019-12-28 05:52:44
#include <stdio.h> #include <stdlib.h> #include <assert.h> static inline int conflict(int *stack, int i, int j) { int k; for (k = 0; k < i; k++) { if (j == stack[k] || abs(i - k) == abs(j - stack[k])) { return 1; } } return 0; } static inline void push(int *stack, int row, int col) { stack[row] = col; } static inline int pop(int *stack, int row) { int col = stack[row]; stack[row] = -1; return col; } static inline int top(int *stack, int n) { int row; for (row = n - 1; row >= 0; row--) { if (stack[row] != -1) { return row; } } return 0; } static char **solution(int *stack, int n) { int row, col; char **solution = (char **)malloc(n*sizeof(char *)); for (row = 0; row < n; row++) { char *line = (char *)malloc(n + 1); for (col = 0; col < n; col++) { line[col] = col == stack[row] ? 'Q' : '.'; } line[n] = '\0'; solution[row] = line; } return solution; } char*** solveNQueens(int n, int *returnSize) { int row = 0, col = 0, sum = 0; char ***solutions = (char ***)malloc(1000 * sizeof(char **)); int *stack = (int *)malloc(n * sizeof(int)); for (row = 0; row < n; row++) { stack[row] = -1; } if (n == 1) { stack[0] = 0; solutions[0] = solution(stack, n); *returnSize = 1; return solutions; } for (; ;) { for (; row < n; row++) { while (col < n) { if (conflict(stack, row, col)) { while (col == n - 1) { if (--row < 0) { free(stack); *returnSize = sum; return solutions; } col = pop(stack, row); } col++; } else { push(stack, row, col); break; } } col = 0; } row = top(stack, n); if (row == n - 1) { solutions[sum++] = solution(stack, n); } col = pop(stack, row); col++; } assert(0); } int main(int argc, char **argv) { int i, n, row, col, num_of_solution; if (argc != 2) { printf("Usage:queen 8"); printf("\n"); exit(-1); } n = atoi(argv[1]); char ***solutions = solveNQueens(n, &num_of_solution); for(i= 0;i<num_of_solution;i++) { char **solution = solutions[i]; for (row = 0; row < n; row++) { char *line = solution[row]; for (col = 0; col < n; col++) { putchar(line[col]); } putchar(' '); } printf("The %dth solution.", i + 1); } return 0; }
...全文
9 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
源代码大师 2021-05-06
  • 打赏
  • 举报
回复
希望对你有帮助:https://blog.csdn.net/it_xiangqiang/category_10581430.html 希望对你有帮助:https://blog.csdn.net/it_xiangqiang/category_10768339.html

69,370

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧