圖論——鄰接矩陣
聲明
本小節針對的圖是簡單無向無權圖,對於圖的基本知識,例如什麼是簡單圖,請自行百度。
圖的鄰接矩陣
對於上圖的鄰接矩陣A如下
0 1 1 0
1 0 0 1
1 0 0 1
0 1 1 0
矩陣A的A[0][1]=1代表從頂點0到頂點1有邊
代碼實現
public class AdjMatrix {
private int V;//頂點數
private int E;//邊數
private int[][] adj;//鄰接矩陣
public AdjMatrix(String filename){
File file = new File(filename);
try(Scanner scanner = new Scanner(file)){
V = scanner.nextInt();//頂點數
if(V<=0) throw new RuntimeException("頂點個數必須大於0");
adj = new int[V][V];
E = scanner.nextInt();//邊數
if(E<0) throw new RuntimeException("邊數不能爲負數");
for(int i=0;i<E;i++){
int a = scanner.nextInt();
validateVertex(a);
int b = scanner.nextInt();
validateVertex(b);
//自環邊檢測
if(a==b){
throw new RuntimeException("簡單圖不能包含自環邊");
}
//平行邊檢測
if(adj[a][b]==1){
throw new RuntimeException("簡單圖不能包含平行邊");
}
adj[a][b] = 1;
adj[b][a] = 1;
}
}catch (IOException e){
e.printStackTrace();
}
}
private void validateVertex(int v){
if(v<0||v>=V){
throw new RuntimeException("頂點下標溢出");
}
}
public int vertexNum(){
return V;
}
public int edgeNum(){
return E;
}
public boolean hasEdge(int v,int w){
validateVertex(v);
validateVertex(w);
return adj[v][w]==1;
}
//鄰接頂點
public List<Integer> adj(int v){
validateVertex(v);
List<Integer> list = new ArrayList<>();
for(int i=0;i<V;i++){
if(adj[v][i]==1){
list.add(i);
}
}
return list;
}
//度
public int degree(int v){
validateVertex(v);
int degree = 0;
for(int i=0;i<V;i++){
if(adj[v][i]==1){
degree++;
}
}
return degree;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("V = %d,E = %d\n",V,E));
for(int i=0;i<adj.length;i++){
for(int j=0;j<adj[0].length;j++){
sb.append(adj[i][j]+" ");
}
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
AdjMatrix adjMatrix = new AdjMatrix("graph.txt");
System.out.println(adjMatrix);
System.out.println(adjMatrix.degree(6));
}
}
graph.txt
7 6
0 1
0 2
1 3
2 6
2 3
1 4
複雜度分析
時間複雜度:
建圖:O(E)
判斷兩個頂點是否有邊:O(1)
求一個頂點的鄰接頂點:O(V)
求一個頂點的度:O(V)
空間複雜度:O(V^2)
很容易看出來空間複雜度對於稀疏圖是極大的浪費,而我們生活中的場景建模出來通常都是稀疏圖,下一小節將介紹另一種存儲方式鄰接表