C语言:最小生成树之kruskal算法
来源:优易学  2011-9-4 16:26:49   【优易学:中国教育考试门户网】   资料下载   IT书店

 

  for(j=0;j<num;j++)
  {
  path[j][0]=0;
  path[j][1]=0;
  }
  for(j=0;j<num;j++)
  {
  status=0;
  for(k=0;k<num;k++)
  if(G[j][k]<maxright)
  {
  status=1;
  break;
  }
  if(status==0)
  break;
  }
  for(i=0;i<num-1&&status;i++)
  {
  for(j=0;j<num;j++)
  for(k=0;k<num;k++)
  if(G[j][k]<min&&!used[j][k])
  {
  v1=j;
  v2=k;
  min=G[j][k];
  }
  if(!used[v1][v2])
  {
  used[v1][v2]=1;
  used[v2][v1]=1;
  touched[v1][v2]=1;
  touched[v2][v1]=1;
  path[0]=v1;
  path[1]=v2;
  for(t=0;t<record;t++)
  FindCircle(path[t][0],path[t][0],num,path[t][0]);
  if(circle)
  {/*if a circle exsits,roll back*/
  circle=0;
  i--;
  exsit=0;
  touched[v1][v2]=0;
  touched[v2][v1]=0;
  min=maxright;
  }
  else
  {
  record++;
  min=maxright;
  }
  }
  }
  if(!status)
  printf("We cannot deal with it because the graph is not connected!\n");
  else
  {
  for(i=0;i<num-1;i++)
  printf("Path %d:vertex %d to vertex %d\n",i+1,path[0]+1,path[1]+1);
  }
  return 1;
  }
  int FindCircle(int start,int begin,int times,int pre)
  { /* to judge whether a circle is produced*/
  int i;
  for(i=0;i<times;i++)
  if(touched[begin]==1)
  {
  if(i==start&&pre!=start)
  {
  circle=1;
  return 1;
  break;
  }
  else
  if(pre!=i)
  FindCircle(start,i,times,begin);
  else
  continue;
  }
  return 1;
  }

上一页  [1] [2] 

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训