学习数据结构基础,如有错误,请指正。
(图的广度优先遍历算法部分,存在错误,请高手帮小弟看下)
/************************************************************************ 数据结构:图的实现,并对其进行深度优先、广度优先遍历 ************************************************************************/ #ifndef __GRAPH_H__ #define __GRAPH_H__ typedef struct ArcNode_stru { int index; struct ArcNode_stru *next; } ArcNode; typedef struct VNode_stru { int data; ArcNode *firstArc; } VNode; class Graph { public: Graph(); ~Graph(); void creatGraph(); int firstAdj(int id); int nextAdj(int id); void depthFirstSearch(int id); void breadthFirstSearch(int id); void travel_DFS(); void travel_BFS(); private: VNode G[5]; int visited[5]; }; #endif // __GRAPH_H__ #include "Graph.h" #include <iostream> #include <list> using std::cout; using std::cin; using std::endl; using std::list; Graph::Graph() { creatGraph(); } Graph::~Graph() { delete []G; } void Graph::creatGraph() { cout<<"input five vertex data:"; for (int i=0;i<5;++i) { cin>>G[i].data; G[i].firstArc = NULL; visited[i] = 0; } int e; ArcNode *node,*preNode; for (int i=0;i<5;++i) { cout<<"input "<<i+1<<"th vertex's edges:"<<endl; cin>>e; while(e != -1) { node = new ArcNode(); node->index = e; node->next = NULL; if (G[i].firstArc == NULL) { G[i].firstArc = node; } else { preNode->next = node; } preNode = node; cin>>e; } } // end for } int Graph::firstAdj(int id) { if (G[id].firstArc != NULL) { return G[id].firstArc->index; } return -1; } int Graph::nextAdj(int id) { ArcNode *p = G[id].firstArc; while (p != NULL) { if ( visited[p->index] == 1) { p = p->next; } else { return p->index; } } return -1; } // 仅适用于连通图 void Graph::depthFirstSearch(int id) { cout<<G[id].data; visited[id] = 1; int tmp_id = this->firstAdj(id); while( tmp_id != -1) { if (visited[tmp_id] == 0) { this->depthFirstSearch(tmp_id); } tmp_id = this->nextAdj(id); } } // 仅适用于连通图
// 存在错误,请指教 void Graph::breadthFirstSearch(int id) { cout<<G[id].data; visited[id] = 1; int index = -1; list<int> *q = new list<int>; q->push_back(id); while(0 != q->size() ) { int count = q->size(); list <int>::iterator item = q->begin(); list <int>::iterator pre_item = q->begin(); for (;item!=q->end();++item) { pre_item = item; } index = *pre_item; int tmp = this->firstAdj(index); while (tmp != -1) { if (visited[tmp] == 0) { cout<<G[tmp].data; visited[tmp] = 1; q->push_back(tmp); } tmp = this->nextAdj(index); } tmp = this->nextAdj(index); } } void Graph::travel_DFS() { for (int i=0;i<5;++i) { if (visited[i] == 0) { this->depthFirstSearch(i); } } } void Graph::travel_BFS() { for (int i=0;i<5;++i) { if (visited[i] == 0) { this->breadthFirstSearch(i); } } } void main() { Graph *g = new Graph(); //g->travel_DFS(); g->travel_BFS(); getchar(); } // end