前向星存儲圖結構
鏈式前向星存儲圖結構
package graphModel;
import java.util.Arrays;
public class Graph {
public static int inf = 1000;// 用於申請大數組,防止越界,同時也表示兩點之間不連接
private Edge[] edges;// 存儲邊的數組
private int[] head;// 鏈式前向星存儲圖結構
private int cnt;// 用於鏈式前向星存儲圖結構
private int[][] indexOfEdge;//已知from和to節點,輸出from-to這條邊在edges數組內的索引
public Graph(int N) {//N爲頂點個數
edges = new Edge[N*(N-1)];
head = new int[N];
Arrays.fill(head, -1);
indexOfEdge = new int[N][N];
for(int i=0 ;i <N; i++)
for(int j=0; j<N; j++)
indexOfEdge[i][j]=inf;
this.cnt = 0;
}
public void addEdge(int u, int v, int w) {
edges[cnt] = new Graph.Edge();
edges[cnt].w = w;
edges[cnt].to = v;
edges[cnt].next = head[u];
head[u] = cnt;
indexOfEdge[u][v] = cnt;
cnt++;
}
/**
* 將鄰接矩陣存儲的圖轉爲鏈式前向星存儲 用於解決最大流問題
*
* @param dag
*/
public void initSolveMaxFlow(int[][] dag) {
for (int i = 0; i < dag.length; i++) {
for (int j = dag.length - 1; j >= 0; j--) {
if (i != j && dag[i][j] < inf) {
this.addEdge(i, j, dag[i][j]);
this.addEdge(j, i, 0);
}
}
}
}
/**
* 將鄰接矩陣存儲的圖轉爲鏈式前向星存儲 用於解決非最大流問題,例如單源最短路徑
*
* @param dag
*/
public void init(int[][] dag) {
for (int i = 0; i < dag.length; i++) {
for (int j = dag.length - 1; j >= 0; j--) {
if (i != j && dag[i][j] < inf) {
this.addEdge(i, j, dag[i][j]);
}
}
}
}
public Edge[] getEdges() {
return this.edges;
}
public int[] getHead() {
return this.head;
}
public int[][] getIndexOfEdge(){
return this.indexOfEdge;
}
class Edge {
Edge() {
}
int next;
int to;
int w;
}
}