如何使用Java中的函数来实现图的遍历算法?
发布时间:2023-12-01 00:38:28
在Java中,图可以通过邻接矩阵或邻接表的形式表示。接下来,我将分别介绍使用函数来实现图的深度优先遍历算法(DFS)和广度优先遍历算法(BFS)。
1. 深度优先遍历算法(DFS):
深度优先遍历算法是一种递归算法,用于搜索或遍历图或树的数据结构。它从一个顶点开始,通过递归地访问相邻的顶点,直到没有未访问的顶点为止。以下是使用函数实现图的深度优先遍历算法的代码示例:
import java.util.ArrayList;
import java.util.List;
class Graph {
private int numVertices; // 顶点数量
private List<List<Integer>> adjacencyList;
public Graph(int numVertices) {
this.numVertices = numVertices;
this.adjacencyList = new ArrayList<List<Integer>>(numVertices);
for (int i = 0; i < numVertices; i++) {
this.adjacencyList.add(new ArrayList<Integer>());
}
}
public void addEdge(int source, int destination) {
this.adjacencyList.get(source).add(destination);
}
public void DFS(int vertex, boolean[] visited) {
visited[vertex] = true;
System.out.print(vertex + " ");
for (int adjacentVertex : this.adjacencyList.get(vertex)) {
if (!visited[adjacentVertex]) {
DFS(adjacentVertex, visited);
}
}
}
public void depthFirstTraversal(int startVertex) {
boolean[] visited = new boolean[this.numVertices];
DFS(startVertex, visited);
}
}
public class Main {
public static void main(String[] args) {
Graph graph = new Graph(5);
graph.addEdge(0, 1);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(4, 0);
System.out.print("DFS Traversal: ");
graph.depthFirstTraversal(0);
System.out.println();
}
}
2. 广度优先遍历算法(BFS):
广度优先遍历算法是一种使用队列的非递归算法,用于搜索或遍历图或树的数据结构。它从一个顶点开始,首先访问其所有未访问的邻居顶点,然后按顶点加入的先后顺序依次访问其邻居的邻居,直到队列为空。以下是使用函数实现图的广度优先遍历算法的代码示例:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
class Graph {
private int numVertices; // 顶点数量
private List<List<Integer>> adjacencyList;
public Graph(int numVertices) {
this.numVertices = numVertices;
this.adjacencyList = new ArrayList<List<Integer>>(numVertices);
for (int i = 0; i < numVertices; i++) {
this.adjacencyList.add(new ArrayList<Integer>());
}
}
public void addEdge(int source, int destination) {
this.adjacencyList.get(source).add(destination);
}
public void BFS(int startVertex) {
boolean[] visited = new boolean[this.numVertices];
Queue<Integer> queue = new LinkedList<Integer>();
visited[startVertex] = true;
queue.offer(startVertex);
while (!queue.isEmpty()) {
int vertex = queue.poll();
System.out.print(vertex + " ");
for (int adjacentVertex : this.adjacencyList.get(vertex)) {
if (!visited[adjacentVertex]) {
visited[adjacentVertex] = true;
queue.offer(adjacentVertex);
}
}
}
}
public void breadthFirstTraversal(int startVertex) {
BFS(startVertex);
}
}
public class Main {
public static void main(String[] args) {
Graph graph = new Graph(5);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(2, 0);
graph.addEdge(2, 3);
graph.addEdge(3, 3);
System.out.print("BFS Traversal: ");
graph.breadthFirstTraversal(2);
System.out.println();
}
}
上述代码示例中,我们首先定义了一个Graph类,该类使用邻接表表示图,并提供了添加边和遍历的方法。然后,在main方法中创建一个图对象,并添加边。最后,调用对应的遍历方法来打印遍历结果。
以上就是使用Java中的函数实现图的遍历算法的基本示例。你可以根据实际需求和数据结构的不同,调整代码来适配不同的图表示方式。
