美文网首页
广度优先搜索

广度优先搜索

作者: 海卓治 | 来源:发表于2017-05-06 22:52 被阅读0次
    #include <bits/stdc++.h>
    #define N 10001
    using namespace std;
    
    int n, m;
    int head[N], sumedge;
    bool vis[N];
    
    struct Edge {
        int x, y, z, next;
        Edge(int x = 0, int y = 0, int z = 0, int next = 0) :
            x(x), y(y), z(z), next(next) {}
    } edge[N * 2];
    
    void ins(int x, int y, int z) {
        edge[++sumedge] = Edge(x, y, z, head[x]);
        head[x] = sumedge;
        return;
    }
    
    void bfs() {
        queue<int> q;
        vis[1] = 1;
        q.push(1);
        while (q.size()) {
            int t = q.front();
            printf("%d ", t);
            q.pop();
            for (int u = head[t]; u; u = edge[u].next) {
                if (!vis[edge[u].y] && edge[u].z != 0) {
                    vis[edge[u].y] = 1;
                    q.push(edge[u].y);
                }
            }
        }
    }
    
    int main() {
        scanf("%d%d", &n, &m);
        for (int i = 1; i <= m; i++) {
            int x, y;
            scanf("%d%d", &x, &y);
            ins(x, y, 1);
        }
        bfs();
    }
    

    相关文章

      网友评论

          本文标题:广度优先搜索

          本文链接:https://www.haomeiwen.com/subject/rjbytxtx.html