描述
图的广度优先搜索类似于树的按层次遍历,即从某个结点开始,先访问该结点,然后访问该结点的所有邻接点,再依次访问各邻接点的邻接点。如此进行下去,直到所有的结点都访问为止。在该题中,假定所有的结点以“A”--“Z”中的若干字符表示,且要求结点的访问顺序要求根据由“A”至“Z”的字典顺序进行访问。例如有如下图:
如果要求从H开始进行广度优先搜索,则搜索结果为:H->A->E->K->U.
输入
输入只包含一个测试用例,第一行为一个自然数n,表示顶点的个数,第二行为n个大写字母构成的字符串,表示顶点,接下来是为一个n*n大小的矩阵,表示图的邻接关系。数字为0表示不邻接,否则为相应的边的长度。
最后一行为一个字符,表示要求进行广度优先搜索的起始顶点。
输出
用一行输出广度优先搜索结果,起始点为给定的顶点,各顶点之间用一个空格隔开。要求同一顶点的邻接点的访问顺序按“A”---“Z”的字典顺序。
样例输入
5
HUEAK
0 0 2 3 0
0 0 0 7 4
2 0 0 0 0
3 7 0 0 1
0 4 0 1 0
H
HUEAK
0 0 2 3 0
0 0 0 7 4
2 0 0 0 0
3 7 0 0 1
0 4 0 1 0
H
样例输出
H A E K U
#include<iostream>
using namespace std;
typedef struct
{
int ch[100][100];
}MG;
typedef struct node
{
int adjvex;
struct node *next;
}ArcNode;
typedef struct
{
ArcNode *first;
}VNode;
typedef struct
{
VNode adjlist[100];
}ALG;
int len;
char c[100];
void turn(ALG *&G,MG g)
{
int i,j;
ArcNode *p;
G = new ALG;
for(i=1;i<=len;i++)
G->adjlist[i].first=NULL;
for(i=1;i<=len;i++)
for(j=1;j<=len;j++)
if(g.ch[i][j])
{
p = new ArcNode;
p->adjvex=j;
p->next=G->adjlist[i].first;
G->adjlist[i].first=p;
}
}
void BFS(ALG *G,int v)
{
ArcNode *p;
int queue[100],front=0,rear=0,j,t;
int visited[100],i,w,a[100],o;
for(i=1;i<=len;i++)
visited[i]=0;
cout<<c[v];
visited[v]=1;
rear+=1;
queue[rear]=v;
while(front!=rear)
{
front+=1;
w=queue[front];
p = G -> adjlist[w].first;
while(p!=NULL)
{
o=0;
while(p!=NULL)
{
if(visited[p->adjvex]==0)
a[o++]=p->adjvex;
p = p->next;
}
if(o==0)break;
for(i=0;i<o-1;i++)
for(j=0;j<o-i-1;j++)
if(c[a[j]]>c[a[j+1]])
{
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
cout<<" "<<c[a[0]];
visited[a[0]]=1;
rear+=1;
queue[rear]=a[0];
p = G->adjlist[w].first;
}
}
}
int main()
{
int i,j;
MG GG;
ALG *G;
char ch;
while(cin>>len)
{for(i=1;i<=len;i++)
cin>>c[i];
for(i=1;i<=len;i++)
for(j=1;j<=len;j++)
cin>>GG.ch[i][j];
cin>>ch;
for(i=1;i<=len;i++)
if(ch==c[i])break;
turn(G,GG);
BFS(G,i);
cout<<endl;
}
return 0;
}