图的深搜

通用模板(思路)

DFS(u)
{
	visit[u]=true;
	for(从u出发所能到达的所有顶点v)
	{
		if visit[v]==false
			DFS(v)
	}
}

DFSTrave(G)
{
	for(G的所有顶点u)
		if visit[u]==false
			DFS(u); 
}
const int maxv=1000;
const int inf=1000000000000;

1、邻接矩阵版DFS

//邻接矩阵版DFS
int n,G[maxv][maxv];
bool vis[maxv]={false};

void DFS(int u,int depth) 
{
	vis[u]=true;
	for(int v=0;v<n;v++)
	{
		if(vis[v]==false&&G[u][v]!inf)
		{
			DFS(v,depth+1);
		}
	}
	
}

void DFSTrave()
{
	for(int u=0;u<n;u++)
	{
		if(vis[u]==false)
		{
			DFS(u,1);
		}
	}	
}

2、邻接表版DFS

//邻接表版DFS
vector<int> adj[maxv];
int n;
bool vis[maxv]={false};

void DFS(int u,int depth)
{
	vis[u]=true;
	for(int i=0;i<adj[u].size();i++)
	{
		int v=adj[u][i];  //vector内所存元素是节点u的邻接节点 
		if(vis[v]==false)
		{
			DFS(v,depth+1);
		}
	}	
}

void DFSTrave()
{
	for(int u=0;u<n;u++)
	{
		if(vis[u]==false)
		{
			DFS(u,1);
		}
	}
}
发布了175 篇原创文章 · 获赞 64 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/OpenStack_/article/details/104069793