图论04-【无权无向】-图的广度优先遍历

文章目录

  • [1. 代码仓库](#1. 代码仓库)
  • [2. 广度优先遍历图解](#2. 广度优先遍历图解)
  • 3.主要代码
  • [4. 完整代码](#4. 完整代码)

1. 代码仓库

https://github.com/Chufeng-Jiang/Graph-Theory

2. 广度优先遍历图解

3.主要代码

  1. 原点入队列
  2. 原点出队列的同时,将与其相邻的顶点全部入队列
  3. 下一个顶点出队列
  4. 出队列的同时,将与其相邻的顶点全部入队列
cpp 复制代码
private void bfs(int s){ //使用循环
    Queue<Integer> queue = new LinkedList<>();
    queue.add(s);
    visited[s] = true;
    while(!queue.isEmpty()){ //只要不是空就不停地出队
        int v = queue.remove(); // v记录队首元素 | 相邻顶点入队后,重新进入while循环,队首出队
        order.add(v); //添加到order数组中,order数组装的是按照BFS顺序遍历的顶点

        for(int w: G.adj(v))
            if(!visited[w]){
                queue.add(w); // 相邻的顶点入队列
                visited[w] = true;
            }
    }
}

复杂度:O(V+E)

4. 完整代码

输入文件

bash 复制代码
7 9
0 1
0 3
1 2
1 6
2 3
2 5
3 4
4 5
5 6
cpp 复制代码
package Chapt04_BFS_Path._0401_Graph_BFS_Queue;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class GraphBFS {

    private Graph G;
    private boolean[] visited;

    private ArrayList<Integer> order = new ArrayList<>(); // 存储遍历顺序

    public GraphBFS(Graph G){
        this.G = G;
        visited = new boolean[G.V()];

        //遍历所有连通分量
        for(int v = 0; v < G.V(); v ++)
            if(!visited[v])
                bfs(v);
    }

    private void bfs(int s){ //使用循环
        Queue<Integer> queue = new LinkedList<>();
        queue.add(s);
        visited[s] = true;
        while(!queue.isEmpty()){ //只要不是空就不停地出队
            int v = queue.remove(); // v记录队首元素 | 相邻顶点入队后,重新进入while循环,队首出队
            order.add(v); //添加到order数组中,order数组装的是按照BFS顺序遍历的顶点

            for(int w: G.adj(v))
                if(!visited[w]){
                    queue.add(w); // 相邻的顶点入队列
                    visited[w] = true;
                }
        }
    }

    //取出遍历顺序
    public Iterable<Integer> order(){
        return order;
    }

    public static void main(String[] args){

        Graph g = new Graph("g1.txt");
        GraphBFS graphBFS = new GraphBFS(g);
        System.out.println("BFS Order : " + graphBFS.order());
    }
}
相关推荐
信奥卷王3 小时前
[GESP202609 六级] 分树规划
算法
夏幻灵3 小时前
LeetCode 21:合并两个有序链表——双指针与哑节点详解
算法·leetcode·链表
徐小黑ACG5 小时前
Golang 基础05 结构体struct
开发语言·算法·golang
Navigator_Z5 小时前
LeetCode //C - 1286. Iterator for Combination
c语言·算法·leetcode
北极有牛6 小时前
cpp学习笔记--常量指针
java·开发语言·算法
GPU实战笔记6 小时前
云端 GPU 训练的账户余额提醒:它能说明什么,不能说明什么?
深度学习·算法·成本管理·gpu云计算·云端训练
浮链序6 小时前
怎么证明"你这个模型是偷我的"——把蒸馏变成取证工具
算法·安全·llm
小O的算法实验室6 小时前
IEEE TMC,面向异构物联网的多目标量子行为拓扑优化算法
算法
liliangcsdn7 小时前
派息率指标的应用探索和分析
大数据·算法