zoukankan      html  css  js  c++  java
  • 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;
    }
     
  • 相关阅读:
    1. Window环境下
    A-Frame 简介03
    A-frame_02
    A-Frame_简单介绍
    iOS_UIWebView加载本地html文件路径问题
    AVAudioRecorder 录制音频
    内存管理, 对象的生命周期
    02-socket编程
    01-socket第三方库 AsyncSocket(GCDAsyncSocket)
    01-MKNetworkKit介绍及使用
  • 原文地址:https://www.cnblogs.com/markliu/p/2495930.html
Copyright © 2011-2022 走看看