1. 图的表示:邻接矩阵,邻接表
2. 图的遍历:广度优先遍历,深度优先遍历(非递归)
3. 注:BFS通常用于从某个源节点开始,寻找最短路径距离,DFS通常作为另一个算法的一个子程序。
1) Edge.h
}
static Edges* _instance;
};
// static variable initialization
Edges* Edges::_instance = NULL;
ostream& operator <<(ostream& os, Edges *q){
if(!q){
cerr << "null Edges!" << endl;
}else{
Edge* p = q->head;
while(p){
os << p << " ";
p = p->next;
}
os << endl;
}
return os;
}
#endif /*EDGE_H_*/
2) Graph.h
3) GraphBuilder.h
4) List.h
5) Test.cpp
Edges* edges = Edges::getInstance();
for(int i = 0; i < sizeof(e)/sizeof(Edge); i++){
edges->insert(&(e[i]));
}
// AdjMatrixGraph *g1 = new AdjMatrixGraph(5, edges);
// MatrixGraphBuilder* mgb = MatrixGraphBuilder::getInstance();
// g1->build(mgb);
// g1->display();
// g1->bfs(0);
// Graph *g1t = g1->getTranspose();
// g1t->display();
// g1t = g1->getSquare();
// g1t->display();
AdjListGraph *g2 = new AdjListGraph(6, edges);
ListGraphBuilder *lgb = ListGraphBuilder::getInstance();
g2->build(lgb);
g2->display();
// Graph *g2t = g2->getTranspose();
// g2t->display();
// g2t = g2->getSquare();
// g2t->display();
// g2->bfs(0);
// g2->diameter();
g2->dfs();
return 0;
}
6) 测试结果