#include <iostream> #include <queue> using namespace std; #define MaxVertex 250 /*测试数据*/ /* 8 9ABCDEFGH 0 1 0 2 1 3 1 4 3 7 4 7 2 5 2 6 5 6 */ /*结果*/ /* A C B G F E D H A C G F B E H D */ bool visited[MaxVertex]; struct ArcNode { int adjvex; ArcNode *next; }; struct Vertext { char date; ArcNode *firstedge; }; struct ALGraph { Vertext V[MaxVertex]; int vernum,arcnum; }; void CreateALGraph(ALGraph *G) { int i,j,k; ArcNode *p; cin>>G->vernum>>G->arcnum; for (i=0;i<G->vernum;i++) { cin>>G->V[i].date; G->V[i].firstedge = NULL; } for (k=0;k<G->arcnum;k++) { cin>>i>>j; p = new ArcNode; p->adjvex = j; p->next = G->V[i].firstedge; 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] = true; 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] = true; Q.push(Node); } p = p->next; } } } void DFS(ALGraph *G,int Node) { ArcNode *p; if (!visited[Node]) { cout<<G->V[Node].date<<" "; visited[Node] = true; p = G->V[Node].firstedge; } while (p) { Node = p->adjvex; if (!visited[Node]) { DFS(G,Node); } p = p->next; } } int main() { freopen("e://2.txt","r",stdin); ALGraph *G = new ALGraph; CreateALGraph(G); cout<<"广度优先搜索:"; BFS(G,0); cout<<endl; cout<<"深度优先搜索:"; memset(visited,0,sizeof(visited)); DFS(G,0); cout<<endl; delete G; return 0; }