用 java语言以测试驱动开发实现图的遍历算法:深度搜索和广度搜索。
时间: 2024-06-10 22:10:09 浏览: 105
这里提供一个简单的实现示例,使用邻接表表示图,以及队列和栈分别实现广度搜索和深度搜索。
首先,定义一个表示图的类,包含节点数和邻接表:
```java
public class Graph {
private int V; //节点数
private LinkedList<Integer>[] adj; //邻接表
public Graph(int V) {
this.V = V;
adj = new LinkedList[V];
for (int i = 0; i < V; i++) {
adj[i] = new LinkedList<>();
}
}
public void addEdge(int u, int v) {
adj[u].add(v);
adj[v].add(u);
}
public int getV() {
return V;
}
public LinkedList<Integer>[] getAdj() {
return adj;
}
}
```
然后,定义一个图的遍历类,包含深度搜索和广度搜索的实现:
```java
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class GraphTraversal {
public void DFS(Graph graph, int start) {
boolean[] visited = new boolean[graph.getV()];
Stack<Integer> stack = new Stack<>();
stack.push(start);
while (!stack.isEmpty()) {
int node = stack.pop();
if (!visited[node]) {
visited[node] = true;
System.out.print(node + " ");
LinkedList<Integer> neighbors = graph.getAdj()[node];
for (int neighbor : neighbors) {
if (!visited[neighbor]) {
stack.push(neighbor);
}
}
}
}
}
public void BFS(Graph graph, int start) {
boolean[] visited = new boolean[graph.getV()];
Queue<Integer> queue = new LinkedList<>();
queue.offer(start);
while (!queue.isEmpty()) {
int node = queue.poll();
if (!visited[node]) {
visited[node] = true;
System.out.print(node + " ");
LinkedList<Integer> neighbors = graph.getAdj()[node];
for (int neighbor : neighbors) {
if (!visited[neighbor]) {
queue.offer(neighbor);
}
}
}
}
}
}
```
最后,可以编写一些测试用例来测试这些遍历算法的正确性:
```java
public class GraphTraversalTest {
@Test
public void testDFS() {
Graph graph = new Graph(6);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(3, 5);
GraphTraversal traversal = new GraphTraversal();
traversal.DFS(graph, 0);
//期望的遍历顺序为:0 2 3 5 4 1
}
@Test
public void testBFS() {
Graph graph = new Graph(6);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
graph.addEdge(3, 5);
GraphTraversal traversal = new GraphTraversal();
traversal.BFS(graph, 0);
//期望的遍历顺序为:0 1 2 3 4 5
}
}
```
以上就是用 java语言以测试驱动开发实现图的遍历算法:深度搜索和广度搜索的方法。
阅读全文