#include <iostream> #include <queue> #include <fstream> #define MaxVertex 250 using namespace std; ifstream cin1("e://graphlist.txt"); /*底下为测试数据 8 9ABCDEFGH 0 1 0 2 1 3 1 4 3 7 4 7 2 5 2 6 5 6 */ int visited[MaxVertex];//全局变量,标记结点是否被访问过 struct ArcNode //边表结构体 { int adjvex; ArcNode *next; }; struct Vertex //顶点结构体 { char Date; ArcNode *firstedge; }; struct ALGraph //无向图结构体 { Vertex V[MaxVertex]; int vernum,arcnum; }; void CreateALGraph(ALGraph *G);//创建无向连通图 void BFS(ALGraph *G,int Node);//广度优先搜索,Node指明要从Node结点开始BFS int main() { ALGraph *G; G = new ALGraph; CreateALGraph(G); BFS(G,0); cout<<endl; delete G; return 0; } void CreateALGraph(ALGraph *G) { int i,j,k; ArcNode *p; cin1>>G->vernum>>G->arcnum; for (i=0;i<G->vernum;i++) { cin1>>G->V[i].Date; G->V[i].firstedge = NULL; } for (k=0;k<G->arcnum;k++) { cin1>>i>>j; p = new ArcNode; p->adjvex = j; p->next = G->V[i].firstedge;//p指向V[i]这个结点所指向的第一个结点,用到的是倒插法 G->V[i].firstedge = p; } } void BFS(ALGraph *G,int Node) { ArcNode *p; queue<int>Q; if (!visited[Node]) { cout<<G->V[Node].Date<<" "; visited[Node] = 1; Q.push(Node);//入队 } while (!Q.empty()) { Node = Q.front();//取出队头元素 Q.pop();//出队 p = G->V[Node].firstedge; while (p) { Node = p->adjvex; if (!visited[Node]) { cout<<G->V[Node].Date<<" "; visited[Node] = 1; Q.push(Node); } p = p->next; } } }