转的算法~~图的广度搜索!按照字典…

来源:互联网 发布:mac系统官方下载地址 编辑:程序博客网 时间:2024/05/19 17:57
Input
第一行为一个自然数n,表示顶点的个数,第二行为n个大写字母构成的字符串,表示顶点,接下来是为一个n*n大小的矩阵,表示图的邻接关系。数字为0表示不邻接,否则为相应的边的长度。最后一行为一个字符,表示要求进行广度优先搜索的起始顶点。
Output
用一行输出广度优先搜索结果,起始点为给定的顶点,各顶点之间用一个空格隔开。要求同一顶点的邻接点的访问顺序按“A”---“Z”的字典顺序。

Sample Input

5HUEAK0 0 2 3 00 0 0 7 42 0 0 0 03 7 0 0 10 4 0 1 0H

Sample Output

HAEKU

下面是源代 !!!
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
int n;
#define NUM 100
char str[NUM];

struct Node{
int index;  //改点在邻接表中的下标
Node *next;
};

struct open{
char s;
bool visited;
Node *first;
}openA[NUM];

struct Temp{
char s;
int id;
};

bool cmp(Temp a,Temp b){
return a.s<b.s;
}

int main(){
char s;
while(cin>>n){
cin>>str;
int i,j,e,k=0;
for(i=0;i<n;i++){//初始化邻接表
openA[i].s=str[i];
openA[i].visited=false;
openA[i].first=NULL;
}
Node *p;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
cin>>e;
if(e){  //构造邻接表
p=new Node;
p->index=j;
p->next=openA[i].first;
openA[i].first=p;
}
}
}
cin>>s;
for(i=0;i<n;i++){
if(str[i]==s)
break;
}
queue<int> Q;
Q.push(i);
openA[i].visited=true;
cout<<str[i];
Temp t[NUM];
int c,bj=i;
while(!Q.empty()){
c=0;
j=Q.front();
//A[j].visited=true;
if(bj!=j)
cout<<str[j];
Node *q;
q=openA[j].first;
//cout<<q->index<<endl;
while(q){ //找到与该点相连的所有未访问过的结点,保存到数组t中
if(!openA[q->index].visited){
openA[q->index].visited=true;
t[c].id=q->index;
t[c].s=openA[q->index].s;
c++;
}
q=q->next;
}
sort(t,t+c,cmp); //按字典顺序搜索
for(i=0;i<c;i++)
Q.push(t[i].id);
Q.pop();  //访问过的节点出队
}
}
return 0;
}

 
0 0
原创粉丝点击