图的深度优先遍历(DFS)

图的深度优先遍历类似于树的先序遍历,不同之处是为了避免重复访问,采用全局数组存储结点是否已经被访问的信息,对于邻接表而言,找邻接点所需的时间取决于顶点个数和边的个数,因此时间复杂度为o(n+e),如果把图的深度优先遍历过程所遍历的边保留,把其余边删掉,那么会形成一颗树。


#define MaxSize 5
#define INF 100

//邻接表
typedef struct ArcNode{
     
    int adjvex;
    struct ArcNode* nextArc;
}ArcNode;

typedef struct{
     
    char data;
    ArcNode* firstArc;
}VNode;

typedef struct{
     
    VNode adjList[MaxSize];
    int n;
    int e;
}AGraph;

int visit[MaxSize];

void initAGraph(AGraph* &G){
     
    G->e = 2;
    G->n = 3;
    cout<<"data:"<<endl;
    for (int i = 0; i < G->n; i++) {
     
        cin>>G->adjList[i].data;
        G->adjList[i].firstArc = NULL;
    }
    cout<<"vi,vj"<<endl;
    for (int j = 0; j < G->e; j++) {
     
        int vi,vj;
        cin>>vi>>vj;
        ArcNode* node = new ArcNode();
        node->adjvex = vj;
        node->nextArc = G->adjList[vi].firstArc;
        G->adjList[vi].firstArc = node;
    }
}

void DFS(AGraph *G,int v){
     
    ArcNode *p;
    visit[v] = 1;
    cout<<"current:"<<G->adjList[v].data<<endl;
    p = G->adjList[v].firstArc;
    while (p != NULL) {
     
        if (visit[p->adjvex] == 0) {
     
            DFS(G, p->adjvex);
            p = p->nextArc;
        }
    }
}

int main(int argc, const char * argv[]) {
     
    AGraph* G = new AGraph();
    initAGraph(G);
    for (int i = 0; i < G->e; i++) {
     
        if (visit[i] == 0) {
     
            DFS(G, i);
        }
    }
    return 0;
}

你可能感兴趣的:(数据结构和算法,数据结构)