广搜与深搜

广度优先搜索

 

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <queue>

using namespace std;
const int N = 10005;

bool vis[N];
int cnt,n,m;
queue<int> Q;
int head[N],to[N],next[N],w[N];
int T[N],ct;

void Init()
{
    ct = 0;
    cnt = 0;
    memset(head,-1,sizeof(head));
}

void add(int u,int v,int c)
{
    to[cnt] = v; w[cnt] = c; next[cnt] = head[u]; head[u] = cnt++;
    to[cnt] = u; w[cnt] = c; next[cnt] = head[v]; head[v] = cnt++;
}

void BFS(int s)
{
    memset(vis,false,sizeof(vis));
    while(!Q.empty()) Q.pop();
    vis[s] = true;
    T[ct++] = s;
    Q.push(s);
    while(!Q.empty())
    {
        int u = Q.front();
        Q.pop();
        for(int i=head[u]; ~i; i=next[i])
        {
            int v = to[i];
            if(!vis[v])
            {
                vis[v] = true;
                T[ct++] = v;
                Q.push(v);
            }
        }
    }
}

int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        Init();
        for(int i=1;i<=n;i++)
        {
            int u,v;
            scanf("%d%d",&u,&v);
            add(u,v,1);
        }
        BFS(1);
        for(int i=0;i<ct;i++)
            cout<<T[i]<<" ";
        puts("");
    }
    return 0;
}


 

深度优先遍历 

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <queue>

using namespace std;
const int N = 10005;

bool vis[N];
int cnt,n,m;
int head[N],to[N],next[N],w[N];
int T[N],ct;

void Init()
{
    ct = 0;
    cnt = 0;
    memset(head,-1,sizeof(head));
    memset(vis,false,sizeof(vis));
}

void add(int u,int v,int c)
{
    to[cnt] = v; w[cnt] = c; next[cnt] = head[u]; head[u] = cnt++;
    to[cnt] = u; w[cnt] = c; next[cnt] = head[v]; head[v] = cnt++;
}

void DFS(int s)
{
    vis[s] = true;
    T[ct++] = s;
    for(int i=head[s]; ~i; i=next[i])
    {
        int v = to[i];
        if(!vis[v])
        {
            printf("%d, %d\n",s,v);
            DFS(v);
        }
    }
}

int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        Init();
        for(int i=1;i<=n;i++)
        {
            int u,v;
            scanf("%d%d",&u,&v);
            add(u,v,1);
        }
        DFS(1);
        for(int i=0;i<ct;i++)
            cout<<T[i]<<" ";
        puts("");
    }
    return 0;
}


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值