c++ 深度优先算法
#include <iostream> using namespace std; #define VertexNum 9 /*定义顶点数*/ struct Node /*声明图形顶点结构*/ { int Vertex; /*邻接顶点数据*/ struct Node *Next; /*下一个邻接顶点*/ }; typedef struct Node *Graph; /*定义图形结构*/ struct Node Head[VertexNum]; /*顶点数组*/ int Visited[VertexNum]; /*查找记录*/ /*深度优先算法*/ void DFS(int Vertex) { Graph Pointer; Visited[Vertex]=1;//已查找 cout<<Vertex<<"==>"; Pointer=Head[Vertex].Next; while(Pointer!= NULL) { if(Visited[Pointer->Vertex]==0) DFS(Pointer->Vertex); Pointer=Pointer->Next; } } /*建立领接顶点至领接列表内*/ void Create_L_Graph(int Vertex1,int Vertex2) { Graph Pointer; Graph New; New=(Graph)malloc(sizeof(struct Node)); if(New!=NULL) { New->Vertex=Vertex2; New->Next=NULL; Pointer=&(Head[Vertex1]); while(Pointer->Next!=NULL) Pointer=Pointer->Next; Pointer->Next=New; } } /*输出领接列表内数据*/ void Print_L_Graph(struct Node *Head) { Graph Pointer; Pointer=Head->Next; while(Pointer!=NULL) { cout<<"["<<Pointer->Vertex<<"]"; Pointer=Pointer->Next; } cout<<endl; } /*主程序*/ void main() { int Node[20][2]={{1,2},{2,1},{1,3},{3,1},{2,4}, {4,2},{2,5},{5,2},{3,6},{6,3}, {3,7},{7,3},{4,8},{8,4},{5,8}, {8,5},{6,8},{8,6},{7,8},{8,7} }; for(int i=0;i<VertexNum;i++) { Head[i].Vertex=i; Head[i].Next=NULL; } for(int i=0;i<VertexNum;i++) Visited[i]=0; for(int i=0;i<20;i++) Create_L_Graph(Node[i][0],Node[i][1]); cout<<"##Graph##"<<endl; for(int i=1;i<VertexNum;i++) { cout<<"Vertex["<<i<<"]:"; Print_L_Graph(&Head[i]); } cout<<"Depth-First-Search:"<<endl; cout<<"[BEGIN]==>"; DFS(1); cout<<"END"; }
书搞进脑袋 创新 创造; 积极