1. 程式人生 > >樹的鄰接表儲存 以及BFS和DFS遍歷

樹的鄰接表儲存 以及BFS和DFS遍歷

程式碼中用到的變數及陣列的作用解析:
1. 變數cnt:用於迭代存入所有的邊
2. head[x]陣列:head[x]表示的是x最後讀入的出邊的編號(x為樹的一個節點)
3. e[max*2]陣列:表示樹中所有邊(例如e[0]表示第0號邊)
4. vis[x]陣列:記錄該節點是否遍歷過,若已遍歷,則不考慮

                                                            建樹以及dfs遍歷

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn=2e5+10;

struct edge
{
    int to;
    int next;
}e[maxn<<1];

int n;
int cnt=-1;
int head[maxn];
bool vis[maxn];

void init()
{
	//memset(e,0,sizeof(e));
    memset(head,-1,sizeof(head));
    memset(vis,false,sizeof(vis));
    cnt=-1;
}
void add_edge(int u,int v)
{
    e[++cnt].to=v;
    e[cnt].next=head[u];
    head[u]=cnt;
}

void dfs(int x)
{
    if(!vis[x])
    {
        cout<<x<<" ";
        vis[x]=1;
        for(int i=head[x];i!=-1;i=e[i].next)
        {
            int d=e[i].to;
            if(!vis[d])
            {
                dfs(d);
            }
        }
    }
}

int main()
{
    while(~scanf("%d",&n))
    {
        init();
        for(int i=1;i<=n-1;i++)
        {
            int u,v;
            cin>>u>>v;
            add_edge(u,v);
            add_edge(v,u);
        }
        dfs(1);
        cout<<endl;
    }
    return 0;
}

                                                                建樹以及bfs遍歷

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=2e5+10;
struct edge
{
    int to,next;
}e[maxn<<1];

int n;
int cnt=-1;
int head[maxn];
int a[maxn];
queue <int> que;
bool vis[maxn];

void init()
{
    memset(head,-1,sizeof(head));
    memset(vis,false,sizeof(vis));
    cnt=-1;
    que.push(1);
}
void add_edge(int u,int v)
{
    e[++cnt].to=v;
    e[cnt].next=head[u];
    head[u]=cnt;
}

void bfs()
{
    while(!que.empty())
    {
        int x=que.front();
        que.pop();
        if(!vis[x])
        {
            cout<<x<<" ";
            vis[x]=1;
        }
        for(int i=head[x];i!=-1;i=e[i].next)
        {
            int d=e[i].to;
            if(!vis[d])
            {
                cout<<d<<" ";
                que.push(d);
                vis[d]=1;
            }
        }
    }
    return ;
}
int main()
{

    while(~scanf("%d",&n))
    {
        init();

        for(int i=1;i<n;i++)
        {
            int u,v;
            scanf("%d%d",&u,&v);
            add_edge(u,v);
            add_edge(v,u);
        }
        bfs();
        cout<<endl;
    }
    return 0;
}

建樹部分理解了好久,尤其是head陣列的作用

個人第一篇部落格,寫的有點嚴肅啊