這裡用鄰接表實現圖的深度優先遍歷,采用遞歸實現。
#includeusing namespace std; #define VERTEXNUM 5//結點數 struct edgenode { int to; int weight; // 邊的權值 edgenode *next; }; struct vnode { int from; edgenode *first; }; void createGraph(vnode *adjilist, int start, int end,int weight); void displayGraph(vnode *adjilist,int nodeNum); void DFT(vnode *adjilist,int* vertexStatusArr,int nodeNum); void DFTcore(vnode *adjilist,int i,int* vertexStatusArr); int main(void){ //創建圖 vnode adjilist[VERTEXNUM]; int nodeNum=VERTEXNUM; for(int i=0;i to=end; p->weight=weight; p->next=adjilist[start].first; adjilist[start].first=p; } //打印存儲的圖 void displayGraph(vnode *adjilist,int nodeNum) { int i,j; edgenode *p; for(i=0;i next; } } } //深度優先遍歷 void DFT(vnode *adjilist, int* vertexStatusArr,int nodeNum) { printf("start BFT graph:\n"); int i; for(i=0;i next) { DFTcore(adjilist, p->to, vertexStatusArr); } }