【模版】无向图的DFS
参考地址:https://blog.csdn.net/weixin_40953222/article/details/80544928
样例
输入:
7 9
0 1
0 2
0 3
2 4
1 4
1 5
3 5
5 6
4 6
输出:
0 1 4 2 6 5 3
代码
#include <iostream>
#include <cstdio>
using namespace std;
#define MVNum 100 //表示最大顶点个数
int visited[MVNum]; //定义一个visited数组,记录已被访问的顶点
/*邻接矩阵存储表示*/
typedef struct Graph{
int arcs[MVNum][MVNum]; //邻接矩阵
int vexnum, arcnum; //当前的顶点数和边数
}Graph;
/*采用邻接矩阵表示法,创建无向图G*/
void CreateUDG(Graph &G){
int v1, v2;
scanf("%d%d", &G.vexnum, &G.arcnum); //输入总顶点数,总边数
for (int i = 0; i < G.vexnum; i++)
for (int j = 0; j < G.vexnum; j++)
G.arcs[i][j] = 0; //初始化邻接矩阵边,0表示顶点i和j之间无边
for (int i = 0; i < G.arcnum; i++){
scanf("%d%d", &v1, &v2); //输入一条边依附的顶点
G.arcs[v1][v2] = G.arcs[v2][v1] = 1; //1表示顶点v1和v2之间有边,无向图不区分方向
}
}
void DFS(Graph &G, int v){
printf("%d ", v); //输出路径
visited[v] = 1;
for (int w = 0; w < G.vexnum; w++)
if (G.arcs[v][w] && !visited[w]) //递归调用
DFS(G, w);
}
int main() {
Graph g;
CreateUDG(g);
DFS(g, 0);
return 0;
}