class Graph
{
private int V; // 节点的数量
private LinkedList<Integer> adj[]; // 邻接表,用于存储图的信息
private Queue<Integer> queue; // 用于在BFS中存储节点
Graph(int v) // 构造函数
{
V = v; // 初始化节点数量
adj = new LinkedList[v]; // 初始化邻接表
for (int i=0; i<v; i++)
{
adj[i] = new LinkedList<>(); // 对邻接表的每个元素进行初始化
}
queue = new LinkedList<Integer>(); // 初始化队列
}
void addEdge(int v,int w) // 添加边的方法
{
adj[v].add(w); // 在邻接表中添加边的信息
}
void DFS(int n) { // 深度优先搜索的主方法
boolean visited[] = new boolean[V]; // 初始化访问数组,用于记录哪些节点已经被访问过
DFSuntil(n, visited); // 从节点n开始进行深度优先搜索
}
void DFSuntil(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]) DFSuntil(n, visited); // 对未访问过的邻居进行深度优先搜索
}
}
void BFS(int n) // 广度优先搜索的方法
{
boolean nodes[] = new boolean[V]; // 初始化访问数组,用于记录哪些节点已经被访问过
int a = 0;
nodes[n]=true;
queue.add(n); // 将节点n添加到队列中
while (queue.size() != 0) // 当队列不为空时
{
n = queue.poll(); // 取出队列中的第一个元素
System.out.print(n+" "); // 输出当前节点
for (int i = 0; i < adj[n].size(); i++) // 遍历当前节点的所有邻居
{
a = adj[n].get(i);
if (!nodes[a]) { // 对未访问过的邻居进行处理
nodes[a] = true;
queue.add(a); // 将未访问过的邻居添加到队列中
}
}
}
}
public static void main(String args[]) // 主方法
{
Graph graph = new Graph(6); // 创建一个有6个节点的图
// 添加边
graph.addEdge(0, 1);
graph.addEdge(0, 3);
graph.addEdge(0, 4);
graph.addEdge(4, 5);
graph.addEdge(3, 5);
graph.addEdge(1, 2);
graph.addEdge(1, 0);
graph.addEdge(2, 1);
graph.addEdge(4, 1);
graph.addEdge(3, 1);
graph.addEdge(5, 4);
graph.addEdge(5, 3);
System.out.println("The Breadth First Traversal of the graph is as follows :");
graph.BFS(0); // 从节点0开始进行广度优先搜索
System.out.print("\n");
System.out.println("The Depth First Traversal of the graph is as follows :");
graph.DFS(0); // 从节点0开始进行深度优先搜索
}
}
[10.4] The Code Implementation of BFS and DFS in Graph
最新推荐文章于 2024-05-22 20:19:20 发布