数据结构之图的广度优先遍历BFS(java)

一、广度优先遍历

  广度优先搜索(Breadth-First-Search, BFS)类似于二叉树的层序遍历算法。基本思想是:

  首先访问起始顶点 v v v,接着由 v v v出发,依次访问 v v v的各个未访问过的邻接顶点 w 1 , w 2 , . . . , w i w_{1},w_{2},...,w_{i} w1w2...wi,然后依次访问 w 1 , w 2 , . . . , w i w_{1},w_{2},...,w_{i} w1w2...wi的所有未被访问过的邻接顶点;再从这些访问过的顶点出发,访问它们所有未被访问过的邻接顶点,直至图中所有顶点都被访问过为止。若此时图中尚有顶点未被访问,则另选图中一个未曾被访问的顶点作为始点,重复上述过程,直至图中所有顶点都被访问到为止。

package com.haiyang.datastructure.graph.bfs;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * 图的初始化
 *
 * @author haiYang
 * @create 2022-01-23 16:06
 */
public class GraphDemo {
    public static void main(String[] args) {
        int n = 5;
        String[] vertexValues = new String[]{"A", "B", "C", "D", "E"};
        Graph graph = new Graph(n);
        for (String vertex : vertexValues) {
            graph.insertVertex(vertex);
        }
        //添加边
        graph.insertEdge(0, 1, 1);
        graph.insertEdge(0, 2, 1);
        graph.insertEdge(1, 2, 1);
        graph.insertEdge(1, 3, 1);
        graph.insertEdge(1, 4, 1);
        graph.showGraph();
        graph.bfs();


    }
}

class Graph {
    private ArrayList<String> vertexList;//存储顶点的集合
    private int[][] edges;//存储图对应的邻接矩阵
    private int numOfEdges;//表示边的个数
    private boolean[] isVisited;//辅助数组,标记顶点是否已经被访问过
    private CircleArrayQueue queue;//使用队列进行广度优先遍历

    public Graph(int n) {
        edges = new int[n][n];
        vertexList = new ArrayList<>(n);
        numOfEdges = 0;
        isVisited = new boolean[n];//初始大小为顶点个数
        queue = new CircleArrayQueue(n + 1);
    }

    /**
     * 对所有顶点进行广度优先遍历
     */
    public void bfs() {
        for (int i = 0; i < getNumOfVertex(); i++) {
            if (!isVisited[i]) {
                bfs(i);
            }
        }
    }


    /**
     * 广度优先遍历
     *
     * @param v 对顶点v进行广度优先遍历
     */
    public void bfs(int v) {
        //访问该顶点
        System.out.println(getValueByIndex(v));
        //标记该顶点已访问
        isVisited[v] = true;
        //顶点v入队列
        queue.addQueue(v);
        while (!queue.isEmpty()) {
            int v1 = queue.getQueue();//队头顶点v1出队列
            //访问v1的所有邻接顶点,并加入队列
            for (int w = getFirstNeighbor(v1); w >= 0; w = getNextNeighbor(v1, w)) {
                if (!isVisited[w]) {
                    System.out.println(getValueByIndex(w));
                    isVisited[w] = true;
                    queue.addQueue(w);
                }
            }
        }
    }

    /**
     * 获取顶点i的第一个邻接顶点
     *
     * @param i 顶点
     * @return 顶点i的第一个邻接顶点
     */
    public int getFirstNeighbor(int i) {
        for (int j = 0; j < vertexList.size(); j++) {
            if (edges[i][j] > 0) {
                return j;
            }
        }
        return -1;
    }

    /**
     * 获取下一个顶点
     *
     * @param i 初始顶点
     * @param j 顶点i的一个邻接顶点
     * @return 顶点j的下一个邻接顶点
     */
    public int getNextNeighbor(int i, int j) {
        for (int k = j + 1; k < vertexList.size(); k++) {
            if (edges[i][k] > 0) {
                return k;
            }
        }
        return -1;
    }

    //获取顶点个数
    public int getNumOfVertex() {
        return vertexList.size();
    }

    public String getValueByIndex(int i) {
        return vertexList.get(i);
    }

    //显示邻接矩阵
    public void showGraph() {
        for (int[] link : edges) {
            System.out.println(Arrays.toString(link));
        }
    }

    //添加顶点
    public void insertVertex(String vertex) {
        vertexList.add(vertex);
    }

    //添加边
    public void insertEdge(int v1, int v2, int weight) {
        edges[v1][v2] = weight;
        edges[v2][v1] = weight;
        numOfEdges++;
    }
}

//队列
class CircleArrayQueue {
    private int maxSize;//环形队列的最大容量
    private int front;//队列头指针
    private int rear;//队列尾指针
    private int[] arr;//用于存取队列中的元素

    public CircleArrayQueue(int arrMaxSize) {
        this.maxSize = arrMaxSize;
        this.arr = new int[maxSize];
    }

    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    public boolean isEmpty() {
        return rear == front;
    }

    public void addQueue(int n) {
        if (isFull()) {
            System.out.println("队列满,不能添加数据");
            return;
        }
        arr[rear] = n;
        rear = (rear + 1) % maxSize;
    }

    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列空,不能取出数据");
        }
        int value = arr[front];
        front = (front + 1) % maxSize;
        return value;
    }

    public void showQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列空,不能取出数据");
        }
        for (int i = front; i < front + size(); i++) {
            System.out.println(i % maxSize + "," + arr[i % maxSize]);
        }
    }

    public int size() {
        return (rear + maxSize - front) % maxSize;
    }

    public int headQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列空,不能取出数据");
        }
        return arr[front];
    }
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HEU_THY

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值