# 如何用回溯法实现

hyqryq 2000-12-19 02:23:00

...全文
187 9 打赏 收藏 举报

9 条回复

hyqryq 2000-12-22

• 打赏
• 举报

lu_yb 2000-12-22
lu_yb@163.net

• 打赏
• 举报

hyqryq 2000-12-22
OK! 多谢多谢！

• 打赏
• 举报

lu_yb 2000-12-22

"最少"是这样得出来的:如果你遍例的所有的情况,那是不是就知道哪种

• 打赏
• 举报

hyqryq 2000-12-22

• 打赏
• 举报

lu_yb 2000-12-21

#include <stdio.h>

#define N 10

int a[N][N] = { 0,1,1,0,1,0,1,0,0,1,
1,0,0,0,0,1,0,0,0,0,
1,0,0,1,0,0,1,0,1,1,
0,0,1,0,0,0,0,1,0,0,
1,0,0,0,0,1,0,0,0,0,
0,1,0,0,1,1,1,1,1,1,
1,0,1,0,0,1,0,0,0,0,
0,0,0,1,0,1,0,0,1,1,
0,0,1,0,0,1,0,1,0,1,
1,0,1,0,0,1,0,1,1,0
};
int w[N+1][N+1] ;
int minnum = N;
int curnum = 0 ;
{
int i,j,k1,k2;
for(i=1;i<=curnum;i++)
{
j=0;
while(w[i][j]!=0&&a[w[i][j]-1][item-1]!=1)
j++;
if(w[i][j]==0)
{
if(item==N)
{
minnum = curnum;
w[i][j] = item;
for(k1=1;k1<=curnum;k1++)
{
k2=0;
printf("%d:",k1);
while(w[k1][k2]!=0)
{
printf(" %d ",w[k1][k2]);
k2++;
}
printf("\n");
}
printf("\n");
w[i][j] = 0;
return;
}
else
{
w[i][j] = item;
}
w[i][j] = 0;
}
}
if(curnum<minnum-1)
{
curnum++;

if(item == N)
{
minnum = curnum;
w[curnum][0]=item;
for(k1=1;k1<=curnum;k1++)
{
k2=0;
printf("%d:",k1);
while(w[k1][k2]!=0)
{
printf(" %d ",w[k1][k2]);
k2++;
}
printf("\n");
}
printf("\n");
w[curnum][0] = 0;
curnum--;
return;
}
else
{
w[curnum][0]=item;
}
w[curnum][0] = 0;
curnum--;
}
return;
}

int main()
{
w[1][0]=1;
curnum = 1;
printf("min number is %d\n",minnum);
}
• 打赏
• 举报

lu_yb 2000-12-21

#define N ...;
int a[N+1][N+1] = {...}; //关联矩阵,如果i和j发生反应a[i][j]=1
int w[N][N]; //仓库内容,初始化为全0
int minnum = N; //仓库最小数
int curnum = 0 ; //目前使用仓库数
{
int i,j;
for(i=1;i<=curnum;i++)
{
j=0; //j代表i仓库中的第j个物品
while(w[i][j]!=0&&a[w[i][j]][item]!=1) //查看i仓库是否能放入item
j++;
if(w[i][j]==0) //如果能放入,则放入i仓库并递进
{
if(item==N)
{
minnum = curnum;
return;
}
else
{
w[i][j] = item;
}
//如果发生递归,则从仓库中取出item
w[i][j] = 0;
}
}
//到此代表已有的仓库均不能放入item或者已经遍例过放入item的情况
//则加入一个仓库
if(curnum<minnum-1)
{
curnum++;
if(item == N)
{
minnum = curnum;
return;
}
else
{
w[curnum][0]=item;
}
w[curnum][0] = 0;
curnum--;
}
return;
}

int main()
{
w[1][0]=1;
printf("min number is %d",minnum);
}
• 打赏
• 举报

wistaria 2000-12-19

• 打赏
• 举报

eball 2000-12-19
n=1; //仓库数
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
if (不发生反应){
put;
goto NEXTGOODS;
}
}
n+=1;
put;
NEXTGOODS:
}
• 打赏
• 举报

3.2w+

2000-12-19 02:23