图的表示
(1)邻接矩阵(adjacency matrix)
(2)邻接表(adjacency lists)
图G=(V, E)的邻接表表示由一个包含|V|个链表的数组Adj所组成,其中每个链表对应于V中的一个顶点。对于每一个u属于V,邻接表Adj[u]包含所有满足条件(u, v)属于E的顶点v。
(3)邻接集(adjacency sets)
(4)边数组(array of edges):所有边构成的数组。
一般稀疏图使用邻接表,稠密图使用邻接矩阵。
图的操作
添加一条边
删除一条边
添加一个顶点
删除一个顶点
可以使用map替换array,set替换list,来方便进行更多的操作。
通过辅助数组,在图遍历的过程中,可以获取(保存)很多有用信息。
package mygraph;
import edu.princeton.cs.algs4.*;
import myutil.*;
public class MyGraph {
private int V; // number of vertices
private int E; // number of edges
private MyList<Integer>[] adj; // adjacency lists
private Point2D[] points;
// @SuppressWarnings("unchecked")
@SuppressWarnings("unchecked")
public MyGraph(int v) {
this.V = v;
this.E = 0;
adj = (MyList<Integer>[]) new MyList [v];
for (int i = 0; i < v; i++) {
adj[i] = new MyList<Integer>();
}
}
public MyGraph(In in) {
this(in.readInt());
int e = in.readInt();
for (int i = 0; i < e; i++) {
int v = in.readInt();
int w = in.readInt();
addEdge(v, w);
}
}
public int V() {
return V;
}
public int E() {
return E;
}
public void addEdge(int v, int w) {
adj[v].addFirst(w);
adj[w].addFirst(v);
E++;
}
public boolean hasEdge(int v, int w) {
for (int u : adj[v]) {
if (u == w) {
return true;
}
}
return false;
}
public Iterable<Integer> adj(int v) {
return adj[v];
}
public String toString() {
String s = V + " vertices, " + E + " edges\n";
for (int v = 0; v < V; v++) {
s += v + ": ";
for (int w : this.adj(v)) {
s += w + " ";
}
s += "\n";
}
return s;
}
/**********************************************/
/* 绘制接口 */
/**********************************************/
public MyGraph(In in, boolean draw) {
this(in.readInt());
StdDraw.setCanvasSize(512 * 2, 512);
MyDraw.setScale(300 * 2, 300);
int n = V();
points = new Point2D[n];
for (int i = 0; i < n; i++) {
points[i] = new Point2D(in.readInt(), in.readInt());
MyDraw.drawCircle(points[i]);
StdDraw.text(points[i].x(), points[i].y()-1, String.valueOf(i));
}
int e = in.readInt();
for (int i = 0; i < e; i++) {
int v = in.readInt();
int w = in.readInt();
addEdge(v, w);
MyDraw.drawLine(points[v], points[w]);
}
}
/* 帮助函数便于画点画线 */
public Point2D getPoint(int v) {
return points[v];
}
public static void main(String[] args) {
MyGraph G = new MyGraph(new In("tinyG1.txt"), true);
int s = 0;
System.out.println(s);
System.out.println(G.V());
System.out.println(G.E());
System.out.println(G.toString());
}
}
来源:CSDN
作者:jiangxt211
链接:https://blog.csdn.net/jiangxt211/article/details/104629704