无向图与图的遍历
Graph Terminology
图论概念的中英文对照表:这些概念的介绍将被省去,因为实在是太过基础了。
- Graph. Set of vertices(顶点)connected pairwise by edges(边).
- Path. Sequence of vertices connected by edges.
- Cycle. Path whose first and last vertices are the same.
- Directed graphs (Digraph). Set of vertices connected pairwise by directed edges.
Cycle-related problems.
- Is there a cycle in the graph?
- Euler tour(欧拉回路): It there a cycle that uses each edge exactly once.
- Hamilton tour(哈密顿回路): Is there a cycle that uses each vertex exactly once.
Connectivity problems.
- Connectivity. Is there a way to connect all of the vertices?
- MST. What is the best way to connect all of the vertices?
- Biconnectivity. Is there a vertex whose removal disconnects the graph?
Graph representation problems.
- Graph isomorphism. Are two graphs identical except for vertex names?
- Planarity. Can we lay out a graph in the plane without crossing edges?
- Topological sort. Can we draw a diagraph so that all edges point upwards?
Graph Processing Design
Graph API.
java
public class Graph {
Graph(int V); // create an empty graph with V vertices
Graph(In in); // create a graph from input stream
void addEdge(int v, int w); // add an edge v-w
Iterable<Integer> adj(int v); // vertices adjacent to v
int V(); // number of vertices
int E(); // number of edges
String toString(); // string representation
}
Adjacency-matrix graph representation.(邻接矩阵表示)
Adjacency-list (undirected) graph representation.(邻接表表示)
java
public class Graph {
private final int V;
private Bag<Integer>[] adj;
public Graph(int V) {
this.V = V;
adj = (Bag<Integer>[]) new Bag[V];
for (int v = 0; v < V; ++v)
adj[v] = new Bag<Integer>();
}
public void addEdge(int v, int w) {
adj[v].add(w);
adj[w].add(v);
}
public Iterable<Integer> adj(int v) { return adj[v]; }
}
Design pattern for graph processing. Decouple graph data type from graph processing.
- Create a
Graphobject. - Pass the
Graphto a graph-processing routine. - Query the graph-processing routine for information.
经典的设计原则:对某个数据结构的操作(processing)与该数据结构本身的定义应当是分开的。例如,若我们想要对图进行 DFS,相较于在 Graph 类内部定义 depthFirstPaths 方法,定义一个 DepthFirstPaths 类并与 Graph 类对象进行交互是一个更优美的设计。
java
public class DepthFirstSearch {
private boolean[] marked;
public DepthFirstSearch(Graph G, int s) {
marked = new boolean[G.V()];
dfs(G, s);
}
private void dfs(Graph G, int v) {
marked[v] = true;
for (int w : G.adj(v))
if (!marked[w]) dfs(G, w);
}
public boolean visited(int v) { return marked[v]; }
}