图的DFS遍历

邻接矩阵 节点个数小于1000时一般使用邻接矩阵

const int MAXV = 1000;//最大顶点数
const int INF = 1000000000;
//邻接矩阵
int n, G[MAXV][MAXV];//n为顶点数 MAXV为最大顶点数
bool vis[MAXV] = { false };

void DFS(int u,int depth)//u为当前访问的标号 depth为深度
{
	vis[u] = true;
	for (int i = 0; i < n; i++)
	{
		if (G[u][i] < INF && vis[i] == false)//u i可达并且i未被访问过
			DFS(i, depth + 1);
	}
}
//遍历图G
void DFSTrave()
{
	for (int i = 0; i < n; i++)
	{
		if (vis[i] == false)
			DFS(i, 1);
	}
}

邻接表

#include<vector>
using namespace std;
const int MAXV = 1000;//最大顶点数
const int INF = 1000000000;
int n;//顶点数
vector<int>Adj[MAXV];
bool vis[MAXV] = { false };

void DFS(int u, int depth)
{
	vis[u] = true;
	for (int i = 0; i < Adj[u].size(); i++)
	{
		if(vis[u]==false)
			DFS(Adj[u][i], depth + 1);
	}
}

void DFSTravel()
{
	for (int i = 0; i < n; i++)
	{
		if (vis[i] == false)
			DFS(i, 1);
	}
}
原文地址:https://www.cnblogs.com/code-fun/p/15229463.html