Topological ordering
Definition
A topological ordering of a directed graph G is a a labelling f of G’s nodes such that:
- the f(v)’s are the set {1, 2, …, n}
- $(u, v) \in G => f(u) < f(v) $
Motivation:
sequence tasks while respecting all precedence constraints
Note: G has directed cycle => no topological ordering
Theorem: no directed cycle => can compute topological ordering in O(m+n) time (DFS + book kepping)
Time: O(V+E)
Reason: O(1) per node, O(1) per edge
Correctness: need to show that if (u,v) is an edge, then f(u) < f(v)
- case1 u visited by DFS before v => recursive call corresponding to v finishes before that of u (since DFS) => f(v) > f(u)
- case2: v visited before u => v’s recursive call finishes before u’s even starts => f(v) > f(u)
Examples
Course Schedule
https://www.hrwhisper.me/leetcode-graph/
https://leetcode.com/problems/course-schedule-ii/description/
Union Find
simple version for undirected graph
1234567parent = {}def init(node):if node not in parent:parent[node] = nodedef find(node):# no path compressionreturn node if parent[node] == node else find(parent[node])for directed graph
with path compression
e.g.
https://leetcode.com/problems/redundant-connection/description/
https://leetcode.com/problems/number-of-islands-ii/description/
Floyd Algorithm
正如我们所知道的,Floyd算法用于求最短路径。Floyd算法可以说是Warshall算法的扩展,三个for循环就可以解决问题,所以它的时间复杂度为O(n^3)。
Floyd算法的基本思想如下:从任意节点A到任意节点B的最短路径不外乎2种可能,1是直接从A到B,2是从A经过若干个节点X到B。所以,我们假设Dis(AB)为节点A到节点B的最短路径的距离,对于每一个节点X,我们检查Dis(AX) + Dis(XB) < Dis(AB)是否成立,如果成立,证明从A到X再到B的路径比A直接到B的路径短,我们便设置Dis(AB) = Dis(AX) + Dis(XB),这样一来,当我们遍历完所有节点X,Dis(AB)中记录的便是A到B的最短路径的距离。
|
|