在Java中,一个简单的二维数组邻接矩阵可以这样表示:

java

public class AdjacencyMatrix {

private int[][] matrix; // 二维数组用于存储邻接矩阵

private int vertices; // 图中的顶点数

public AdjacencyMatrix(int vertices) {

this.vertices = vertices;

this.matrix = new int[vertices][vertices];

}

// 设置边的权值

public void setEdge(int source, int destination, int weight) {

matrix[source][destination] = weight;

if (!isDirected()) { // 如果图是无向的,则对称设置权值

matrix[destination][source] = weight;

}

}

// 获取边的权值

public int getEdge(int source, int destination) {

return matrix[source][destination];

}

// 判断是否有边

public boolean hasEdge(int source, int destination) {

return getEdge(source, destination) != 0;

}

// 返回图是否为有向图

public boolean isDirected() {

// 在实际实现中,可能需要根据具体的类属性来判断图的类型

// 这里假设所有的图都是无向的

return false;

}

// 打印邻接矩阵

public void printMatrix() {

for (int i = 0; i < vertices; i++) {

for (int j = 0; j < vertices; j++) {

System.out.print(matrix[i][j] + "\t");

}

System.out.println();

}

}

// 深度优先搜索(DFS)

public void dfs(int vertex, boolean[] visited) {

visited[vertex] = true;

System.out.println("访问顶点: " + vertex);

for (int neighbor = 0; neighbor < vertices; neighbor++) {

if (matrix[vertex][neighbor] != 0 && !visited[neighbor]) {

dfs(neighbor, visited);

}

}

}

// 广度优先搜索(BFS)

public void bfs(int startVertex) {

boolean[] visited = new boolean[vertices];

Queue queue = new LinkedList<>();

visited[startVertex] = true;

queue.add(startVertex);

while (!queue.isEmpty()) {

int current = queue.poll();

System.out.println("访问顶点: " + current);

for (int neighbor = 0; neighbor < vertices; neighbor++) {

if (matrix[current][neighbor] != 0 && !visited[neighbor]) {

visited[neighbor] = true;

queue.add(neighbor);

}

}

}

}

}

这个代码示例包括了一个邻接矩阵的基本操作,如设置和获取边的权值、判断是否有边、打印邻接矩阵以及进行深度优先搜索(DFS)和广度优先搜索(BFS)。请注意,这只是一个基本实现,并没有包含所有可能的功能,例如添加或删除顶点和边等。在实际应用中,你可能需要根据具体的需求进行扩展。