bfs/dfs(邻接表)

#include <iostream>
#include <stdio.h>
#include <string.h>
#define E 500500
#define V 10050
using namespace std;
struct edge
{
    int s,t,next;
}e[E];
int head[V];
int queue[V];
int cnt,n,m,st,end;
int vis[V];
void addedge(int u,int v)
{
    e[cnt].s=u;
    e[cnt].t=v;
    e[cnt].next=head[u];
    head[u]=cnt++;
}
void dfs(int u)
{
    int v;
    vis[u]=1;
    //在这里输入遍历u点时的操作
    for(int k=head[u];k!=-1;k=e[k].next)
    {
        v=e[k].t;
        if(vis[v]==0)
        {
            dfs(v);
            //在这里输入遍历完'u的孩子v点'后对u的操作
        }
    }
    //在这里输入遍历完'u周围各点'后对u的操作
}
void bfs(int u)
{
    int k,v,top=0,tail=0;
    queue[tail++]=u;
    while(top<tail)
    {
        v=queue[top++];
        for(k=head[v];k!=-1;k=e[k].next)
        {
            u=e[k].t;
            if(vis[u]==0)
            {
               vis[u]=1;
                queue[tail++]=u;
                if(u==end) return ;
            }
        }
    }
}
int main()
{
    int a,b;
    while(cin >> n >> m >> st >> end)
    {
        cnt=0;
        memset(head,-1,sizeof(head));
        for(int i=0;i<m;i++)
        {
            cin >> a >> b;
            addedge(a,b);
        }
        memset(vis,0,sizeof(vis));
        dfs(st);
        bfs(st);
        for(int i=0;i<=n;i++)
        {
            cout << vis[i] << " " ;
        }
    }
    return 0;
}
 
原文地址:https://www.cnblogs.com/markliu/p/2495930.html