MIT6.006 lecture10

72 阅读1分钟

DFS & BFS:

DFS different from BFS,it solves the problem about reachability.BFS is to find the shortest path.

So,what we care about is whether we can reach the node, maybe we would gothrough the far path.

Topological Sort:

DAG:

directed acyclic graph,a directed graph that contains no directed cycle.

Topology Order:

for edge(u,v), f(u)<f(v)f(u)< f(v),f is the ordering

Cycle Detection:

Claim: if G contains a cycle,it will traverse from v to v's ancestor.

So,when we traverse the dfs,we record the edge,to check whether it will return back to the source.

def dfs(Adj, s, parent=None, order=None):
    if parent is None:
        parent = [None for x in Adj]
        parent[s] = s
        order = []
    for x in Adj[s]:
        if parent[x] is None:
            parent[x] = s
            dfs(Adj, x, parent, order)
    order.append(s)
    return order, parent
def full_def(Adj):
    parent = [None for x in Adj]
    order = []
    for x in range(len(Adj)):
        if parent[x] is None:
            parent[x] = x
            dfs(Adj, x, parent, order)
    return order, parent