用java编写程序实现如下功能: (1)输入无向图的顶点数、边数及各条边的顶点对,建立用邻接表表示的无向图。 (2)对图进行深度优先搜索和广度优先搜索遍历,并分别输出其遍历序列
时间: 2023-06-19 22:04:19 浏览: 95
以下是实现上述功能的Java代码:
```java
import java.util.*;
public class GraphTraversal {
private int V; // 顶点数
private LinkedList<Integer>[] adjList; // 邻接表
public GraphTraversal(int v) {
V = v;
adjList = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjList[i] = new LinkedList<>();
}
}
public void addEdge(int u, int v) {
adjList[u].add(v);
adjList[v].add(u);
}
public void dfs(int s) {
boolean[] visited = new boolean[V];
dfsUtil(s, visited);
}
private void dfsUtil(int u, boolean[] visited) {
visited[u] = true;
System.out.print(u + " ");
for (int v : adjList[u]) {
if (!visited[v]) {
dfsUtil(v, visited);
}
}
}
public void bfs(int s) {
boolean[] visited = new boolean[V];
Queue<Integer> queue = new LinkedList<>();
visited[s] = true;
queue.add(s);
while (!queue.isEmpty()) {
int u = queue.poll();
System.out.print(u + " ");
for (int v : adjList[u]) {
if (!visited[v]) {
visited[v] = true;
queue.add(v);
}
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入无向图的顶点数:");
int V = scanner.nextInt();
System.out.print("请输入无向图的边数:");
int E = scanner.nextInt();
GraphTraversal graph = new GraphTraversal(V);
System.out.println("请输入各条边的顶点对(用空格隔开):");
for (int i = 0; i < E; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
graph.addEdge(u, v);
}
System.out.print("深度优先遍历序列:");
graph.dfs(0);
System.out.println();
System.out.print("广度优先遍历序列:");
graph.bfs(0);
System.out.println();
}
}
```
示例输入输出:
```
请输入无向图的顶点数:5
请输入无向图的边数:6
请输入各条边的顶点对(用空格隔开):
0 1
0 2
1 2
1 3
2 3
3 4
深度优先遍历序列:0 1 2 3 4
广度优先遍历序列:0 1 2 3 4
```
阅读全文