const int maxn=1000;
const int inf=1e9;
//邻接矩阵版
int n,G[maxn][maxn];
bool vis[maxn]={false};
void dfs(int u,int depth){
vis[u]=true;
for(int v=0;v<n;v++)
if(!vis[v]&&G[u][v]!=inf) dfs(v,depth+1);
}
void dfstrave(){
for(int u=0;u<n;u++)
if(!vis[u]) dfs(u,1);
}
//邻接表版
vector<int> Adj[maxn];
int n;
bool vis[maxn]={false};
void dfs(int u,int depth){
vis[u]=true;
for(int i=0;i<Adj[u].size();i++){
int v=Adj[u][i];
if(!vis[v]) dfs(v,depth+1);
}
}
void dfstrave(){
for(int u=0;u<n;u++)
if(!vis[u]) dfs(u,1);
}
数据结构——图的深度优先搜索模板
最新推荐文章于 2024-08-09 21:26:42 发布