Java:编程实现深度优先搜索遍历和图的广度优先搜索遍历功能
时间: 2024-12-16 16:17:19 浏览: 2
深度优先和广度优先遍历及其java实现
在Java中,我们可以使用递归实现深度优先搜索(Depth First Search, DFS),也可以使用队列数据结构来实现广度优先搜索(Breadth First Search, BFS)。以下是两种搜索算法的基本实现:
**深度优先搜索 (DFS):**
```java
import java.util.Stack;
public class Graph {
private int vertices;
private boolean[][] adj; //邻接矩阵表示
// ...其他方法...
public void dfs(int start) {
boolean[] visited = new boolean[vertices];
dfsUtil(start, visited);
}
private void dfsUtil(int v, boolean[] visited) {
visited[v] = true;
System.out.print(v + " ");
for (int i = 0; i < vertices; i++) {
if (adj[v][i] && !visited[i])
dfsUtil(i, visited);
}
}
}
```
**广度优先搜索 (BFS):**
```java
import java.util.Queue;
import java.util.LinkedList;
public class Graph {
private int vertices;
private boolean[][] adj; //邻接矩阵表示
// ...其他方法...
public void bfs(int start) {
boolean[] visited = new boolean[vertices];
Queue<Integer> queue = new LinkedList<>();
visited[start] = true;
queue.add(start);
while (!queue.isEmpty()) {
int vertex = queue.poll();
System.out.print(vertex + " ");
for (int i = 0; i < vertices; i++) {
if (adj[vertex][i] && !visited[i]) {
visited[i] = true;
queue.add(i);
}
}
}
}
}
```
阅读全文