八皇后问题--to be continued
2018-03-18 10:58
405 查看
#include "stdafx.h" #include <stdlib.h> #include <stdio.h> using namespace std; #define TRUE 1 #define FALSE 0 int nQueens_nonrecursive(int *a, int n)//递归法 { int top, i, j, conflict; top = -1; //初始栈为空 i = 0; //从第0行开始 do { conflict = FALSE; for (j = 0; j < top + 1; j++) { if (i == a[j] || top + 1 - j == i - a[j] || top + 1 == a[j] - i) { conflict = TRUE; } } if (conflict == FALSE) { a[++top] = i; //把当前皇后放在第i列 if (top == n - 1)//problem solved return TRUE; i = 0; } else { while (i == n - 1 && top >= 0)//每次试探最后1列失败,就回溯一步 i = a[top--]; i++; } } while (i < n); return FALSE; } int nQueens(int *a, int k, int n) //设有k个皇后放在前k行某k个不冲突的位置 //这些位置已经被数组a的前k个元素所记录 { int i, j, conflict; if (k == n) return true; for (i = 0; i < n; i++) { conflict = FALSE; for (j = 0; j < k; j++) { //判断把第k+1个皇后放在第k+1行第i列会不会与前k个皇后发生冲突1 if (i == a[j] || k - j == i - a[j] || k - j == a[j] - i) { conflict = TRUE; } } if (conflict == FALSE) { a[k] = i;//如果把第k+1个皇后放在第k+1行 if (nQueens(a, k + 1, n) == TRUE) return TRUE; } } return FALSE; } void printSolution(int *a, int n) { int i, j; printf("\nPlace queens in the following positions:\n"); for (i = 0; i < n; i++) { printf("Row%3d-Col%3d: |", i, a[i]); for (j = 0; j < a[i]; j++) printf("|"); printf("Q|"); for (j = a[i]; j < n; j++) printf("|"); printf("\n"); printf("\n"); } } int main() { int n, *a; a = new int[100]; printf("Please enter an integer as the size of the problem:\n n="); scanf_s("%d", &n); if (n > 0) a = (int *)malloc(n * sizeof(int)); else { printf("Error!Invalid input!\n"); } if (nQueens_nonrecursive(a, n) == TRUE) printSolution(a, n); else printf("Sorry!"); free(a); return 0; }
相关文章推荐
- 由Josephus问题说开去(to be continued)
- 关于联通块DP的一些问题(to be continued)
- Live Migration (SLES10 SP2 XEN) (3-问题篇)TO BE CONTINUED
- 各种怪问题 ...... to be continued
- 解决‘tools.jar’ seems to be not in android studio classpath 问题
- LeetCode Summary - JAVA Version - LinkedList (To be continued)
- 1024.Palindromic Number (25)...to be continued...
- ubuntu下gedit闪退,遇到问题:ERROR:../../gi/pygi-argument.c:1583:_pygi_argument_to_object: code should not be reached 已放弃 (核心已转储)
- 【期刊&&会议】机器学习&&深度学习 + 计算机视觉(To be continued..)
- Device eth0 does not seem to be present, delaying initialization(解决克隆CentOS6.3虚拟机后网卡设备无法启动问题)
- ArrayAdapter requires the resource ID to be a TextView问题
- (1.)javaweb问题解决之Httpservlet cannot be resolved to a type的原因与解决方法
- 1026.Table Tennis (30)...to be continued...
- 1089.Insert or Merge (25)...to be continued...
- Windows多线程编程, to be continued...
- javax.servlet.jsp.PageContext cannot be resolved to a type问题如何解决???
- vmware复制centos虚拟机碰到Device eth0 does not seem to be present的问题
- struts2的<s:iterator>标签 遇到的问题:java.lang.ClassCastException:cannot be cast to java.lang.String
- 回忆moblin ...to be continued
- 问题-Ctrl+F7跟踪值时提示“Function to be called, TGGLPolyhedron3d.AsString, was eliminated by linker”