美文网首页
深度优先搜索

深度优先搜索

作者: 海卓治 | 来源:发表于2017-05-06 23:05 被阅读0次
    #include <bits/stdc++.h>
    #define N 10001
    using namespace std;
    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];
    
    bool vis[N];
    int head[N], sumedge;
    int n, m;
    
    void dfs(int x, int p) {
        printf("%d ", x);
        vis[x] = true;
        for (int u = head[x]; u; u = edge[u].next) {
            if (!vis[edge[u].y] && edge[u].z && edge[u].y != p) {
                dfs(edge[u].y ,x);
            }
        }
    }
    
    void ins(int x, int y) {
        edge[++sumedge] = Edge(x, y, 1, head[x]);
        head[x] = sumedge;
        return;
    }
    
    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);
        }
        dfs(1, -1);
    }
    

    相关文章

      网友评论

          本文标题:深度优先搜索

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