MIT6.006 lecture009

103 阅读1分钟

Graph Defination:

  • Directed edges are ordered edges
  • Undirected edges are unorded edges (i.e. (u,v) and (v,u) are different)
  • E=O(V2)E=O(V^2)
ECn2  (for  undirected)E2Cn2  for  directed|E|\le C_{n}^{2} \;(for \;undirected)\\ |E|\le 2\cdot C_{n}^{2}\;for \;directed

Neighbor Sets:

  • outgoing neighbor set
  • incoming neighbor set
  • out-degree
  • in-degree

Graph Representation:

  • A set to map u to Adj(u)
    • DAA or hash table (lookup fast by vertices)
  • Adjacency list to store Adj(u)
    • array or linked list(usuallt to insert)

Hand shaking lemma:

uVdeg(u)2E\sum_{u \in V} deg(u)\le 2|E|

Path:

  • the lengh l(p): the edges in the path
  • distance δ(u,v)\delta (u,v) is the minimum lengh of the path from u to v.

Graph Path Problem:

  • Single pair reachbility: Is there a path from s to v
  • single pair shortest path: return the shortest path from s to v
  • single source shortest path: return δ(s,v)\delta(s,v) for all v in graph

If we solve one of them,we will find we could solve all them absoloutly.

BFS:

def bfs(Adj, s):
    parent = [None for x in Adj]
    parent[s] = s
    level = [[s]]
    while len(level[-1]) > 0:
        level.append([])  # remember to augment the new level for new items
        for u in level[-2]:
            for v in level[-1]:
                if parent[v] is None:
                    parent[v] = u
                    level[-1].append(v)
    return parent


def unweighed_shortest_path(Adj, s, t):
    parent = bfs(Adj, s)
    # if we can reach t from s
    if parent[t] is None:
        parent[t] = None
    i = t
    path = [t]
    while i != s:
        i = parent[i]
        path.append(i)
    return path[::-1]

Running time:

O(V+E)O(|V|+|E|) ,because we will go through all the vertices,every node,we will go the edges.