java实现图的邻接矩阵(附完整源码)
时间: 2023-10-17 08:27:54 浏览: 49
好的,以下是Java实现图的邻接矩阵的完整源码:
```java
import java.util.*;
public class Graph {
private int[][] adjacencyMatrix;
private int numVertices;
public Graph(int numVertices) {
this.numVertices = numVertices;
this.adjacencyMatrix = new int[numVertices][numVertices];
}
public void addEdge(int i, int j) {
adjacencyMatrix[i][j] = 1;
adjacencyMatrix[j][i] = 1;
}
public void removeEdge(int i, int j) {
adjacencyMatrix[i][j] = 0;
adjacencyMatrix[j][i] = 0;
}
public boolean hasEdge(int i, int j) {
return adjacencyMatrix[i][j] == 1;
}
public List<Integer> outEdges(int i) {
List<Integer> edges = new ArrayList<Integer>();
for (int j = 0; j < numVertices; j++) {
if (hasEdge(i, j)) {
edges.add(j);
}
}
return edges;
}
public List<Integer> inEdges(int i) {
List<Integer> edges = new ArrayList<Integer>();
for (int j = 0; j < numVertices; j++) {
if (hasEdge(j, i)) {
edges.add(j);
}
}
return edges;
}
public void print() {
System.out.println("Adjacency Matrix:");
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
System.out.print(adjacencyMatrix[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Graph graph = new Graph(4);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 0);
graph.print();
System.out.println("Out edges of vertex 2: " + graph.outEdges(2));
System.out.println("In edges of vertex 2: " + graph.inEdges(2));
}
}
```
这段代码实现了一个基本的图类,其中包含了邻接矩阵的实现,包括添加边、删除边、查询边、查询出边和入边等基本操作。在main函数中,我们创建了一个四个节点的图,并添加了四条边,然后打印出了邻接矩阵以及节点2的出边和入边。