1. Topological Sort

topological sort可用来检测是否为DAG(有向无环图)
拓扑排序的两种写法:dfs和bfs
DFS

    public boolean dfs(List<Integer>[] graph, int i, int[] used) {
        if (used[i] == 1)   return false;
        if (used[i] == 2)   return true;
        used[i] = 1;
        for (int next : graph[i]) {
            if (!dfs(graph, next, used))
                return false;
        }
        used[i] = 2;
        res.add(0, i); //topo路径
        return true;
    }

BFS

        // BFS的写法并不需要visited数组
        Queue<Integer> q = new LinkedList<>();
        for (int i = 0; i < numCourses; i ++) {
            if (indegree[i] == 0) //入度为0
                q.offer(i);
        }
        List<Integer> res = new ArrayList<>();
        while (!q.isEmpty()) {
            int cur = q.poll();
            res.add(cur); // topo路径
            for (int next : graph[cur]) {
                if (--indegree[next] == 0)
                    q.offer(next);
            }
        }

如何判断topo路径是否唯一:BFS,每次indegree为0的节点仅有一个

  1. union find
    class UF {
        int[] root;
        public UF(int n) {
            root = new int[n];
            for (int i = 0; i < n; i ++) 
                root[i] = i;
        }
        public boolean union(int i, int j) {
            int pi = find(i);
            int pj = find(j);
            if (pi == pj)   return false;
            root[pi] = pj;
            return true;
        }
        public int find(int i) {
            if (i != root[i])
                root[i] = find(root[i]);
            return root[i];
        }
    }

Union Find的本质是把原本不联通的node连接起来,实现的具体形式并不一定和上面一样。比如每个节点就可以根据横纵坐标encode成String形式的key,用HashMap<String, String>存起来
可根据需要求连通分量个数,各联通分量的大小
261. Graph Valid Tree
树:无向联通无环图,dfs/topo均可解

  1. dfs

Euler Path:每条边都通过且仅通过一次的路径
判断图中是否存在Euler Path:
(1)图联通且无孤立点
(2)无向图:奇数点为0或2
有向图:不存在或仅存在两个点的入度不等于出度
求Euler Path:

void EulerPath(u) {
    for each edge e = (u, v) in E:
        remove(u, v) from E
        EulerPath(v) 
    prepend u to path
}

我想做个正常人
1 声望2 粉丝