当树以无向图的方式,数组模拟的方式 存储(也就是每一条边当成2条有向边存储时),如何使用dfs()遍历每个节点而不重复呢?
示例的代码如下:
int dfs(int u,int father )//father用于防止重复搜索的dfs,使得每个叶子节点只可以搜索一次
{
int depth=0;
for(int i=h[u];i!=-1;i=ne[i])
{
int j=e[i] ;
if (j==father) continue;//过滤掉父节点,让他不能再返回遍历父节点
depth=max(depth,dfs(j,u)+1);
}
return depth;
}
注:这是pat甲级的1021题的代码。以上是他的一部分
- 这个题为什么需要存两个无向图,而不是简单的存一个无向图??
原因是因为每一个点都要当做根来dfs一次,所以必须有两个方向
#include <iostream>
#include <algorithm>
#include <vector>
#include <cstring>
using namespace std;
const int N=10010,M=N*2;
int n;
int p[N];
int h[N],e[M],ne[M],idx;
void add(int a,int b)
{
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
int find(int u)
{
if(p[u]!=u) p[