Graph Defination:
- Directed edges are ordered edges
- Undirected edges are unorded edges (i.e. (u,v) and (v,u) are different)
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:
Path:
- the lengh l(p): the edges in the path
- distance 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 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:
,because we will go through all the vertices,every node,we will go the edges.