Lesson algorithm programmer (18) - Common graph algorithms: breadth-first (BFS)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/m0_37609579/article/details/100110089

First, the breadth-first search Introduction

Breadth-first search algorithm (Breadth First Search), also known as "BFS" ​​or "breadth-first search", referred to BFS.

The idea is: a vertex v from the graph, and then click Access After visiting v individual never visited neighbors v, and then separately from these neighbors in order to visit their neighbors, and making the "first to be accessed adjacent vertex points adjacent vertex dots before access after being accessed, all vertices have been visited neighbors until the figure are accessed. If at this time the figures there have not been accessed vertex, need another is selected from a vertex not been visited as a new starting point, repeating the process until all vertices have been drawing until accessed.

In other words, breadth-first search is a traversal of FIG v as a starting point of the process, from near to far, and v has successively access communication path and a path length of 1, 2, ... vertex.

Second, the breadth-first search illustration

1. No figure breadth-first search

Following the "undirected graph" as an example to demonstrate breadth-first search. FIG G1 or in the above example.

  1. Step 1 : Visit A. 
  2. Step 2 : in order to access C, D, F. After a visit to A, the next adjacent access point A. As already mentioned, in the implementation described herein, the order of the vertices ABCDEFG stored, C in front of "D and F", and therefore, access to C. After re-finished visit C, in turn access D, F. 
  3. Step 3 : sequentially accessing B, G. After the completion of the second step access C, D, F, and then sequentially access their neighbors. First access point adjacency B C, and then access the abutment point F G. 
  4. Step 4 : Access E. In step 3 End Access B, then G, then sequentially access their neighbors. Only G has abutment points E, so adjacent access point G E.

Thus access sequence is: A -> C -> D -> F. -> B -> G -> E

2. breadth-first search graph

Below "directed graph" as an example to demonstrate breadth-first search. FIG G2 or in the above example.

  1. Step 1 : Visit A. 
  2. Step 2 : Access B. 
  3. Step 3 : in order to access C, E, F. After visiting B, the next access another vertex B side, i.e. C, E, F. As already mentioned, in implementations herein, in accordance with the stored vertices ABCDEFG order, therefore to access C, then sequentially accessing E, F. 
  4. Step 4 : sequentially accessing D, G. After completion of accessing C, E, F, and then sequentially access the other side of the apex thereof. According to still have access to all the C, E, F, sequential access, C over, and then only E, F; D E the first access point of abutment, and then access the abutment point F G.

Thus access sequence is: A -> B -> C -> E -> F. -> D -> G

Third, code implementation

Core code:

 
  1.  
    /**
  2.  
    * 图的广度优先遍历算法
  3.  
    */
  4.  
    private void boardFirstSearch(int i) {
  5.  
    LinkedList<Integer> queue = new LinkedList<>();
  6.  
    System.out.println("访问到了:" + i + "顶点");
  7.  
    isVisited[i] = true;
  8.  
    queue.add(i);
  9.  
     
  10.  
    while (queue.size() > 0) {
  11.  
    int w = queue.removeFirst().intValue();
  12.  
    int n = getFirstNeighbor(w);
  13.  
    while (n != -1) {
  14.  
    if (!isVisited[n]) {
  15.  
    System.out.println("访问到了:" + n + "顶点");
  16.  
    isVisited[n] = true;
  17.  
    queue.add(n);
  18.  
    }
  19.  
    n = getNextNeighbor(w, n);
  20.  
    }
  21.  
    }
  22.  
    }
 

Fourth, the DFS and FIG complete code BFS

 
  1.  
    import java.util.LinkedList;
  2.  
     
  3.  
    public class Graph {
  4.  
     
  5.  
    private int vertexSize; // 顶点数量
  6.  
    private int[] vertexs; // 顶点数组
  7.  
    private int[][] matrix; // 包含所有顶点的数组
  8.  
    // 路径权重
  9.  
    // 0意味着顶点自己到自己,无意义
  10.  
    // MAX_WEIGHT也意味着到目的顶点不可达
  11.  
    private static final int MAX_WEIGHT = 1000;
  12.  
    private boolean[] isVisited; // 某顶点是否被访问过
  13.  
     
  14.  
    public Graph(int vertextSize) {
  15.  
    this.vertexSize = vertextSize;
  16.  
    matrix = new int[vertextSize][vertextSize];
  17.  
    vertexs = new int[vertextSize];
  18.  
    for (int i = 0; i < vertextSize; i++) {
  19.  
    vertexs[i] = i;
  20.  
    }
  21.  
    isVisited = new boolean[vertextSize];
  22.  
    }
  23.  
     
  24.  
    /**
  25.  
    * 获取指定顶点的第一个邻接点
  26.  
    *
  27.  
    * @param index
  28.  
    * 指定邻接点
  29.  
    * @return
  30.  
    */
  31.  
    private int getFirstNeighbor(int index) {
  32.  
    for (int i = 0; i < vertexSize; i++) {
  33.  
    if (matrix[index][i] < MAX_WEIGHT && matrix[index][i] > 0) {
  34.  
    return i;
  35.  
    }
  36.  
    }
  37.  
    return -1;
  38.  
    }
  39.  
     
  40.  
    /**
  41.  
    * 获取指定顶点的下一个邻接点
  42.  
    *
  43.  
    * @param v
  44.  
    * 指定的顶点
  45.  
    * @param index
  46.  
    * 从哪个邻接点开始
  47.  
    * @return
  48.  
    */
  49.  
    private int getNextNeighbor(int v, int index) {
  50.  
    for (int i = index+1; i < vertexSize; i++) {
  51.  
    if (matrix[v][i] < MAX_WEIGHT && matrix[v][i] > 0) {
  52.  
    return i;
  53.  
    }
  54.  
    }
  55.  
    return -1;
  56.  
    }
  57.  
     
  58.  
    /**
  59.  
    * 图的深度优先遍历算法
  60.  
    */
  61.  
    private void depthFirstSearch(int i) {
  62.  
    isVisited[i] = true;
  63.  
    int w = getFirstNeighbor(i);
  64.  
    while (w != -1) {
  65.  
    if (!isVisited[w]) {
  66.  
    // 需要遍历该顶点
  67.  
    System.out.println("访问到了:" + w + "顶点");
  68.  
    depthFirstSearch(w); // 进行深度遍历
  69.  
    }
  70.  
    w = getNextNeighbor(i, w); // 第一个相对于w的邻接点
  71.  
    }
  72.  
    }
  73.  
     
  74.  
    /**
  75.  
    * 图的广度优先遍历算法
  76.  
    */
  77.  
    private void boardFirstSearch(int i) {
  78.  
    LinkedList<Integer> queue = new LinkedList<>();
  79.  
    System.out.println("访问到了:" + i + "顶点");
  80.  
    isVisited[i] = true;
  81.  
    queue.add(i);
  82.  
     
  83.  
    while (queue.size() > 0) {
  84.  
    int w = queue.removeFirst().intValue();
  85.  
    int n = getFirstNeighbor(w);
  86.  
    while (n != -1) {
  87.  
    if (!isVisited[n]) {
  88.  
    System.out.println("访问到了:" + n + "顶点");
  89.  
    isVisited[n] = true;
  90.  
    queue.add(n);
  91.  
    }
  92.  
    n = getNextNeighbor(w, n);
  93.  
    }
  94.  
    }
  95.  
    }
  96.  
     
  97.  
    public static void main(String[] args) {
  98.  
    Graph graph = new Graph(9);
  99.  
     
  100.  
    // 顶点的矩阵设置
  101.  
    int[] a1 = new int[] { 0, 10, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, 11, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT };
  102.  
    int[] a2 = new int[] { 10, 0, 18, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, 16, MAX_WEIGHT, 12 };
  103.  
    int[] a3 = new int[] { MAX_WEIGHT, MAX_WEIGHT, 0, 22, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, 8 };
  104.  
    int[] a4 = new int[] { MAX_WEIGHT, MAX_WEIGHT, 22, 0, 20, MAX_WEIGHT, 24, 16, 21 };
  105.  
    //int[] a4 = new int[] { MAX_WEIGHT, MAX_WEIGHT, 22, 0, 20, MAX_WEIGHT, MAX_WEIGHT, 16, 21 };
  106.  
    int[] a5 = new int[] { MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, 20, 0, 26, MAX_WEIGHT, 7, MAX_WEIGHT };
  107.  
    int[] a6 = new int[] { 11, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, 26, 0, 17, MAX_WEIGHT, MAX_WEIGHT };
  108.  
    int[] a7 = new int[] { MAX_WEIGHT, 16, MAX_WEIGHT, 24, MAX_WEIGHT, 17, 0, 19, MAX_WEIGHT };
  109.  
    //int[] a7 = new int[] { MAX_WEIGHT, 16, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, 17, 0, 19, MAX_WEIGHT };
  110.  
    int[] a8 = new int[] { MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, 16, 7, MAX_WEIGHT, 19, 0, MAX_WEIGHT };
  111.  
    int[] a9 = new int[] { MAX_WEIGHT, 12, 8, 21, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, MAX_WEIGHT, 0 };
  112.  
     
  113.  
    graph.matrix[0] = a1;
  114.  
    graph.matrix[1] = a2;
  115.  
    graph.matrix[2] = a3;
  116.  
    graph.matrix[3] = a4;
  117.  
    graph.matrix[4] = a5;
  118.  
    graph.matrix[5] = a6;
  119.  
    graph.matrix[6] = a7;
  120.  
    graph.matrix[7] = a8;
  121.  
    graph.matrix[8] = a9;
  122.  
     
  123.  
    graph.depthFirstSearch(0);
  124.  
    //graph.boardFirstSearch(0);
  125.  
    }
  126.  
     
  127.  
    }
 

V. Summary

  • Breadth-first traversal representation to each layer traversed to traverse the next level .
  • Let's think: Suppose v0there are three adjacent points v1 v2 v3.
    • After our visit v0, then visit v1 v2 v3. After we finished v1 from the start traversing its neighbors, then v2 from traversing its neighbors, and finally traversing v3 from its neighbor.
    • That is, the three neighbors after the visit. We want to come back one by one traverse their neighbors . This I think to use a container to store them down the order. Each time a vertex is then removed from the container traversing header. Here, I think LinkedList, because it fits additions and deletions. And you do not need to traverse the collection here.
  • We can put the first set of vertices, and then while(!queue.isEmpty()), or while(queue.size() > 0)will do. To start the cycle.
    • Then removed and remove the first element adjacent to the first vertex point of collection . The apex of the visit,
      • If the vertex is not visited , visit! Then the vertices in the collection.
      • If the vertex already visited , to find the next neighbor of the vertex.

My micro-channel public number: architecture Scriptures (id: gentoo666), shared Java dry, high concurrency programming, popular technical tutorials, and distributed micro-services technology, architecture, design, block chain technology, artificial intelligence, big data, Java interview questions, as well as cutting-edge information and so popular. Updated daily Oh!

References:

  1. https://blog.csdn.net/Strive_Y/article/details/81810012
  2. https://www.jianshu.com/p/23b55db1adc0

 

Guess you like

Origin www.cnblogs.com/anymk/p/11521524.html