作为一名02后,最讨厌前面的长篇大论
以下是使用Java实现BFS算法的示例代码:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class BFS {
// 定义图的邻接矩阵
private int[][] graph;
// 定义节点数
private int nodeNum;
// 构造函数
public BFS(int[][] graph, int nodeNum) {
this.graph = graph;
this.nodeNum = nodeNum;
}
// BFS算法实现
public void bfs(int start) {
Queue<Integer> queue = new LinkedList<>(); // 存储遍历到的所有节点
ArrayList<Integer> visited = new ArrayList<>(); // 标记已经访问的节点
queue.offer(start); // 将起始节点加入队列
visited.add(start);
while (!queue.isEmpty()) {
int current = queue.poll(); // 取出队首元素
for (int i = 0; i < nodeNum; i++) { // 遍历当前节点的所有邻居节点
if (graph[current][i] == 1 && !visited.contains(i)) { // 如果该邻居节点未被访问过,加入队列
queue.offer(i);
visited.add(i);
}
}
System.out.print(current + " "); // 输出当前节点
}
}
// 测试代码
public static void main(String[] args) {
int[][] graph = {{0, 1, 1, 0, 0, 0},
{1, 0, 0, 1, 1, 0},
{1, 0, 0, 0, 1, 1},
{0, 1, 0, 0, 0, 1},
{0, 1, 1, 0, 0, 1},
{0, 0, 1, 1, 1, 0}};
BFS bfs = new BFS(graph, 6);
bfs.bfs(0); // 从0节点开始遍历
}
}
代码中,我们定义了一个BFS类,并在构造函数中传入图的邻接矩阵和节点数。由于邻接矩阵中1表示两个节点之间存在一条边,因此我们可以通过遍历邻接矩阵中指定节点的所有邻居节点来实现BFS算法。在算法实现过程中,我们使用了Java的Queue和ArrayList两个数据结构来分别存储遍历到的所有节点和标记已经访问的节点。最后,我们在测试代码中创建了一个邻接矩阵,并从节点0开始执行BFS算法。
运行程序,输出结果为:0 1 2 3 4 5,即按照广度优先顺序遍历了整张图。