图的遍历
standford algorithm learning notes
广度优先
Breadth First Search(BFS)
To systematically explore the nodes of the graph beginning with the given starting vertex in layers.
Algorithm
BFS(graph G, start vertex s)
[all nodes initially unexplored]
- mark s as explored.
- let Q = queue data structure (FIFO), initialized with s.
- while Q ≠ ϕ :
- remove the first node from Q, call it v.
- for each edge(v, w):
if w is unexplored:
- mark w as explored
- add w to Q(at the end)
Basic properties
- at the end of BFS, v exposed ↔ G has a path from s to v.
- running time of main while loop = O( ns + ms ), where ns is number of nodes findable from s, ms is number of edges findable from s.
Application : shortest paths
Goal: Compute dist(v), the fewest number of edges on a path from s to v.
Extra code:
- initialize dist(v) = { 0, if v = s; or 1, if v ≠ s
- when considering edge (v, w):
- if w unexplored, then set dist(w) = dist(v) + 1
Claim: at termination, dist(v) = i ↔ v is in i th layer.
深度优先
Depth First Search(DFS)
- much more aggressive search than BFS where you immediately try to plunge as deep as you can only backtracking when absolutely necessary.
- preserve topological ordering in directed graph.
Aogorithm
Recursive version: DFS(graph G, start vertex s)
1. mark s as explored.
2. for every edge(s, v):
- if v unexplored:
- DFS(G, v)
Basic properties
- at the end of the algorithm, v marked as explored
↔ ∃ path from s to v in G.Application: topological ordering
definition: A topological ordering of a directed graph G is a labelling F of G’s nodes such that :
1. the f(v)’s are the set {1,2, … ,n}
2. (u, v) ∈ → f(u) < f(v)topological sort via DFS:
DFS-loop(graph G)
1. mark s as explored.
2. current_label = n[to keep track of ordering]
3. for each vertex v ∈ G:if v unexplored:
DFS(G, v)set f(v) = current_label
current_label −−