基本思路:1.用一个指针数组来存储图的信息 例如 0 3 ; 0 4 ;两组数据之后 head[0]=NULL 变为 head[0]->3->4->NULL , 同理head[3]->0->NULL ; head[4]->0->NULL ;
2.用一个bool类型的vis数组记录路径 (1 0 记录 来过 没来过);
///Accode
#include <bits/stdc++.h> using namespace std; const int maxn=1010; bool vis[maxn]; /// 0 is stand for not came this point typedef struct Graph /// 邻接表 { int data; Graph *next; } Graph,*Gra; Gra head[maxn]; ///指针类型的数组 void Insert(Gra &head,int x) /// 元素插入到邻接表的函数 { Gra q,a,in; in=new Graph; ///in 是要插入的节点 in->data=x; in->next=NULL; if (head==NULL) ///如果 head==null 说明这个节点还没存过元素 所以直接把顶点x插入 { head=new Graph; head->next=in; in->next=NULL; } else ///否则 将顶点插入到最后 { q=head; ///q 是 a 的前驱节点 a=q->next; while (a) { q=q->next; a=a->next; } q->next=in; ///新进来的元素插入尾部 in->next=NULL; } } void BFS (int t) ///广搜 { int now; Gra p,a; vis[t]=1; ///利用vis数组来判断是否来过此点 queue <int> q; q.push(t); while(!q.empty()) { now =q.front(); q.pop(); cout<<now<<" "; if (head[now]) ///如果head[now] 不为空 寻找以它为头节点的链表... { p=head[now]; a=p->next; while (a) { if (!vis[a->data]) { q.push(a->data); vis[a->data]=1; ///标记 "来过" } a=a->next; } } } } int main() { int i,n,k,m,t; int u,v; cin>>n; while (n--) { cin>>k>>m>>t; memset(vis,0,sizeof(vis)); ///visit 数组初始化 for (i=0; i<k; i++) ///head[]初始化,类似邻接矩阵的 0 初始化 { head[i]=NULL; } for (i=1; i<=m; i++) { cin>>u>>v; Insert(head[u],v); Insert(head[v],u); ///无向图 } BFS(t); } return 0; }有关邻接表的传送门 http://blog.csdn.net/gentle_guan/article/details/52222573
