Java实现连通图的深度优先遍历和广度优先遍历
时间: 2024-06-14 17:04:11 浏览: 101
Java实现图的深度优先遍历和广度优先遍历
5星 · 资源好评率100%
以下是Java实现连通图的深度优先遍历和广度优先遍历的示例代码:
1. 深度优先遍历(DFS):
```java
import java.util.*;
class Graph {
private int V; // 顶点的个数
private LinkedList<Integer> adj[]; // 邻接表
// 构造函数
Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}
// 添加边
void addEdge(int v, int w) {
adj[v].add(w);
}
// 递归函数,于深度优先遍历
void DFSUtil(int v, boolean visited[]) {
visited[v] = true;
System.out.print(v + " ");
Iterator<Integer> i = adj[v].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n])
DFSUtil(n, visited);
}
}
// 对给定的顶点进行深度优先遍历
void DFS(int v) {
boolean visited[] = new boolean[V];
DFSUtil(v, visited);
}
}
public class Main {
public static void main(String args[]) {
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println("深度优先遍历结果:");
g.DFS(2);
}
}
```
输出结果:
```
深度优先遍历结果:
2 0 1 3
```
2. 广度优先遍历(BFS):
```java
import java.util.*;
class Graph {
private int V; // 顶点的个数
private LinkedList<Integer> adj[]; // 邻接表
// 构造函数
Graph(int v) {
V = v;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}
// 添加边
void addEdge(int v, int w) {
adj[v].add(w);
}
// 对给定的顶点进行广度优先遍历
void BFS(int s) {
boolean visited[] = new boolean[V];
LinkedList<Integer> queue = new LinkedList<Integer>();
visited[s] = true;
queue.add(s);
while (queue.size() != 0) {
s = queue.poll();
System.out.print(s + " ");
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n]) {
visited[n] = true;
queue.add(n);
}
}
}
}
}
public class Main {
public static void main(String args[]) {
Graph g = new Graph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println("广度优先遍历结果:");
g.BFS(2);
}
}
```
输出结果:
```
广度优先遍历结果:
2 0 3 1
```
阅读全文