谁有"八皇后"原代码?(分不够再加,或者另起一帖加分)

wandou999 2004-04-18 10:39:09
re!!
...全文
81 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
wandou999 2004-04-18
  • 打赏
  • 举报
回复
TO:cngdzhang()
TO:cgsw12345(cgsw)
小弟是学JAVA的,但对C挺感兴趣的,小弟不失言,请cngdzhang() 和cgsw12345(cgsw)
别走开,另起帖加分!!!
cngdzhang 2004-04-18
  • 打赏
  • 举报
回复
tc编写的:
输入皇后的个数即可

#include <stdio.h>
#include <stdlib.h>

int f1[100],f2[100],f3[100],total,p[100],totalmethod;

void print()
{
int i,j;
totalmethod++;
for(i=1;i<=total;i++)
{
for(j=1;j<=total;j++)
{
if(p[j]==i) printf("*");
else printf("-");
}
printf("\n");
}
printf("\nmethod : %d\n\n",totalmethod);
}

int placeable(int i,int j)
{
return(!(f1[i] || f2[i-j+total] || f3[i+j]));
}

void tryit(int n)
{
int i;
for(i=1;i<=total;i++)
{
if(!placeable(i,n)) continue;
f1[i]=1;
f2[i-n+total]=1;
f3[i+n]=1;
p[n]=i;
if(n==total) print();
else tryit(n+1);
f1[i]=0;
f2[i-n+total]=0;
f3[i+n]=0;
p[n]=0;
}
}

void main()
{
int i;
printf("How many queens do you want to place ?");
scanf("%d",&total);
if(total<=0) exit(0);
tryit(1);
}
cgsw12345 2004-04-18
  • 打赏
  • 举报
回复
这是N皇后问题的回溯法,非递归实现.此算法对初学者有难度,最好去参考书.这个问题也是回溯法的经典例题,推荐自己去实践.还有,我贴的程序在TC3.0下调试通过.
#include <iostream.h>
#include <stdio.h>
#include <math.h>
#include <dos.h>
enum bool{false, true};
class Queen{
friend int nQueen(int);
private:
inline bool Place(int k);
void Backtrack(void);
int n, *x;
long sum;
};
inline bool Queen::Place(int k)
{
int j;
for (j = 1; j < k; j++)
if ((abs(k - j) == abs(x[j] - x[k])) || (x[j] == x[k])) return false;
return true;
}
void Queen::Backtrack(void)
{
x[1] = 0;
int k = 1;
while (k > 0){
x[k] += 1;
while ((x[k] <= n) && !(Place(k)))
x[k] += 1;
if (x[k] <= n)
if (k == n)
sum++;
else {
k++;
x[k] = 0;
}
else
k--;
}
}

int nQueen(int n)
{
Queen X;
X.n = n;
X.sum = 0;
int *p = new int[n+1];
for (int i = 0; i <= n; i++)
p[i] = 0;
X.x = p;
X.Backtrack();
delete []p;
return X.sum;
}
int main()
{
int n;
struct time t1, t2; //取系统时间.
gettime (&t1);
cout << "input n = ";
cin >> n;
cout << nQueen(n) << endl;
gettime (&t2);
cout << (t2.ti_sec - t1.ti_sec) + (t2.ti_hund-t1.ti_hund)*1.0/100;
return 0;
}

69,369

社区成员

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

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