publicclassGraph{ privatefinalint V; //num of vertex, 顶点的数目 privateint E; //num of edge private Bag<Integer>[] adj; //邻接表, implement of Bag
publicGraph(int V){ this.V = V; this.E = 0; adj = (Bag<Integer>[]) new Bag[V]; for (int v = 0; v < V; v++) { adj[v] = new Bag<>(); } }
publicintV(){ return V; }
publicintE(){ return E; }
publicvoidaddEdge(int v, int w){ if (v > V || v < 0 || w > V || w < 0) thrownew IllegalArgumentException(); if (v == w) thrownew IllegalArgumentException("Don't allow self-loop!"); if (adj[v].contains(w) || adj[w].contains(v)) thrownew IllegalArgumentException("Don't allow parallel-edge!"); adj[v].add(w); adj[w].add(v); E++; }
publicbooleanhasEdge(int v, int w){ if (V() < 2) returnfalse; if (v < 0 || v >= V()) returnfalse; return adj[v].contains(w); }
public Iterable<Integer> adj(int v){ return adj[v]; } }
public Iterable<Integer> pathTo(int v){ if (!hasPathTo(v)) returnnull; Stack<Integer> path = new Stack<>(); for (int x = v; x != s; x = edgeTo[x]) path.push(x); path.push(s); return path; } }
privatevoidbfs(Graph G, int s){ Queue<Integer> queue = new Queue<>(); marked[s] = true; queue.enqueue(s); while (!queue.isEmpty()) { int v = queue.dequeue(); for (int w : G.adj(v)) { if (!marked[w]) { edgeTo[w] = v; marked[w] = true; queue.enqueue(w); } } } }
public Iterable<Integer> pathTo(int v){ if (!hasPathTo(v)) returnnull; Stack<Integer> path = new Stack<>(); for (int x = v; x != s; x = edgeTo[x]) path.push(x); path.push(s); return path; }
publicintdistTo(int v){ //0~v distance int dis = 0; if (!hasPathTo(v)) return dis; for (int x = v; x != s; x = edgeTo[x]) dis++; return dis; } }