两个城市之间寻找最短路径问题(广度优先搜索)

多个城市之间寻找最短路径《题目可以参照<算法设计与分析*吕国英……清华大学出版社>课本的P186》

#include


int jz[9][9]={{0,0,0,0,0,0,0,0,0},{0,0,1,1,1,0,1,0,0},{0,1,0,0,0,0,1,0,0},{0,1,0,0,1,1,0,0,0},{0,1,0,1,0,0,0,1,0},
 {0,0,0,1,0,0,0,1,1},{0,1,1,0,0,0,0,0,1},{0,0,0,0,1,1,0,0,1},{0,0,0,0,0,1,1,1,0}};

struct {
 int city;
 int pre;
}sq[100];


int qh,qe,i,visited[100];
int n=8;

 

void out()        //输出路径/
{
 printf("可以走的路程的路径为(数字代表城市的编号):/n/n");
 printf("%d ",sq[qe].city);
 while(sq[qe].pre!=0)
 {
  qe=sq[qe].pre;
  printf("-- %d ",sq[qe].city);
 }
 printf("/n/n");
}
void search()
{
 qh=0;
 qe=1;
 sq[1].city=1;
 sq[1].pre=0;
 visited[1]=1;
 while(qh!=qe)//当队不空//  
 {
  qh=qh+1;                         //结点出队/
  for(i=1;i<=n;i++)//扩展结点/
   if(jz[sq[qh].city][i]==1&&visited[i]==0)
   {
    qe=qe+1;                    //结点入队/
    sq[qe].city=i;
    sq[qe].pre=qh;
    visited[i]=1;
    if (sq[qe].city==8)
    {
     out();
     return;
    }
   }
     }
 printf("没有可以走的路!/n");
}

 

void main()
{
 int i;
 for(i=1;i<=n;i++)
 {
  visited[i]=0;
 }

 search();
}

你可能感兴趣的:(编程心得,算法分析与设计)