# sdut oj2107 图的深度遍历(DFS)

```1
4 4
0 1
0 2
0 3
2 3```

## 示例输出

`0 1 2 3`

## 提示

``````#include <bits/stdc++.h>
#include <algorithm>
using namespace std;

int mp[110][110];///地图，用矩阵的方式实现
int vis[110];///标记，看该点是否已经遍历过
int edgenum,vexnum;

void DFS(int n)
{
if(n == 0)
printf("%d",n);
else
printf(" %d",n);
vis[n] = 1;
for(int j = 0;j < vexnum;j++)
{
if(!vis[j] && mp[n][j])
DFS(j);
}
}

int main()
{
int t;
int u,v;
scanf("%d",&t);
while(t--)
{
memset(mp,0,sizeof(mp));
memset(vis,0,sizeof(vis));
scanf("%d%d",&vexnum,&edgenum);
for(int i = 0;i < edgenum;i++)
{
scanf("%d%d",&u,&v);
mp[u][v] = mp[v][u] = 1;
}
DFS(0);
printf("\n");
}
return 0;
}
``````

标准写法：

``````#include <bits/stdc++.h>
using namespace std;
#define maxsize 110

int f;
bool vis[maxsize];
typedef int element;

typedef struct
{
element vex[maxsize];
element arc[maxsize][maxsize];
int vexnum,arcnum;
} Graph;

Graph *Creat_Graph()
{
int u,v;
Graph *G;
G = (Graph *)malloc(sizeof(Graph));
scanf("%d%d",&G->vexnum,&G->arcnum);
for(int i = 0; i < G->vexnum; i++)
G->vex[i] = i;
for(int i = 0; i < G->vexnum; i++)
for(int j = 0; j < G->vexnum; j++)
G->arc[i][j] = 0;
for(int i = 0; i < G->arcnum; i++)
{
scanf("%d%d",&u,&v);
G->arc[u][v] = G->arc[v][u] = 1;
}
return G;
}

void DFS(Graph *G,int n)
{
vis[n] = true;
printf(f ? "%d" : " %d",G->vex[n]);
f = 0;
for(int i = 0; i < G->vexnum; i++)
{
if(G->arc[n][i]&&!vis[i])
DFS(G,i);
}
}

void DFSTraverse(Graph *G)
{
for(int i = 0; i < G->vexnum; i++)
vis[i] = false;
for(int i = 0; i < G->vexnum; i++)
{
if(!vis[i])
DFS(G,i);
}
}

int main()
{
int t;
scanf("%d",&t);
while(t--)
{
Graph *G;
G = Creat_Graph();
f = 1;
DFSTraverse(G);
printf("\n");
}
return 0;
}
``````

原文作者：数据结构之图
原文地址: https://blog.csdn.net/Annfan123/article/details/52218358
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。