在Java中使用函数实现图的深度优先遍历算法
发布时间:2023-07-01 13:37:28
图的深度优先遍历算法是一种遍历图中所有节点的方式,它通过访问一个节点后继续访问该节点的邻接节点,直到所有节点都被访问过为止。在Java中,我们可以通过递归函数来实现该算法。
首先,我们需要定义一个图的类,其中包含图的节点和边的信息。在本例中,我们使用邻接矩阵来表示图的节点和边的关系。假设图的节点数为n,邻接矩阵的大小为n×n,矩阵中的元素a[i][j]表示节点i到节点j之间是否存在一条边。如果存在一条边,a[i][j]的值为1;否则,为0。
public class Graph {
private int[][] adjacencyMatrix;
private int numberOfNodes;
public Graph(int numberOfNodes) {
this.numberOfNodes = numberOfNodes;
this.adjacencyMatrix = new int[numberOfNodes][numberOfNodes];
}
public void addEdge(int source, int destination) {
adjacencyMatrix[source][destination] = 1;
}
public void depthFirstTraversal(int startNode) {
boolean[] visited = new boolean[numberOfNodes];
depthFirstTraversal(startNode, visited);
}
private void depthFirstTraversal(int current, boolean[] visited) {
visited[current] = true;
System.out.print(current + " ");
for (int i = 0; i < numberOfNodes; i++) {
if (adjacencyMatrix[current][i] == 1 && !visited[i]) {
depthFirstTraversal(i, visited);
}
}
}
}
在上述代码中,我们首先定义了一个Graph类,其中的addEdge方法用于添加节点之间的边。depthFirstTraversal方法是对外的接口,它调用了私有的depthFirstTraversal方法,并传入一个boolean数组visited来标记哪些节点已经被访问过。depthFirstTraversal方法先将当前节点标记为已访问,并输出节点的值;然后,遍历当前节点的邻接节点,并递归的调用depthFirstTraversal方法,直到所有节点都被访问过为止。
接下来,我们可以使用下列代码来测试上述代码:
public class Main {
public static void main(String[] args) {
Graph graph = new Graph(6);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 4);
graph.addEdge(3, 4);
graph.addEdge(3, 5);
graph.addEdge(4, 5);
System.out.println("Depth First Traversal (starting from vertex 0):");
graph.depthFirstTraversal(0);
}
}
运行上述代码,我们将得到如下输出:
Depth First Traversal (starting from vertex 0): 0 1 3 4 5 2
这表明,从节点0开始进行深度优先遍历,按照节点的编号依次访问了所有节点。
