邻接矩阵DFS遍历(递归以及非递归)

#include <iostream>
#include <stack>
#include <queue>
#include <cstdio>
#define MAXVEX 100
#define TRUE 1
#define FALSE 0
#define MAX 100
#define INFINITY 65535
using namespace std;

typedef char VertexType;
typedef int EdgeType;
bool visited[MAX];

typedef struct{
    VertexType vexs[MAXVEX];
    EdgeType arc[MAXVEX][MAXVEX];
    int numVertexes, numEdges;
}MGraph;

void CreateMGraph(MGraph *G){
    int i, j, k, w;
    printf("input num_vertexes and num_edges:
");
    scanf("%d %d", &G->numVertexes, &G->numEdges);
    getchar();
    printf("input vertexes_name:
");
    for(i=0; i<G->numVertexes;i++){//输入结点
        scanf("%c", &G->vexs[i]);
        getchar();
    }
    for(i=0;i<G->numVertexes;i++)
        for(j=0;j<G->numVertexes;j++)
            G->arc[i][j]=INFINITY;
    printf("input edges(vi,vj) i,j and w:
");
    for(k=0;k<G->numVertexes;k++){
        scanf("%d %d %d",&i,&j,&w);
        G->arc[i][j]=w;
        G->arc[j][i]=G->arc[i][j];
    }
}

void DFS(MGraph G, int i ){
    int j;
    visited[i]=TRUE;
    printf("%c ", G.vexs[i]);
    for(j=0;j<G.numVertexes;j++){
        if(G.arc[i][j]==1&&!visited[j])
            DFS(G, j);
    }
}

void DFSTraverse(MGraph G){
    int i;
    for(i=0;i<G.numVertexes;i++)
        visited[i] = FALSE;
    for(i=0;i<G.numVertexes;i++)
        if(!visited[i])
            DFS(G, i);
}
int main(){
    MGraph G;
    CreateMGraph(&G);
    DFS(G, 0);
    printf("
");
    DFSTraverse(G);
    return 0;
}
/*
5 4
A
B
C
D
E
0 1 1
0 4 1
1 2 1
4 2 1
2 3 1
*/

  

原文地址:https://www.cnblogs.com/coodyz/p/10894459.html