Home  >  Article  >  Backend Development  >  Breadth-first search does not use queues

Breadth-first search does not use queues

WBOY
WBOYforward
2023-09-16 21:57:031157browse

Breadth-first search does not use queues

Breadth First, Look (BFS) is a graph traversal calculation used to study the center of breadth movement in a graph. Normal use of BFS utilizes the line information structure to keep track of incoming hubs. Regardless, it is conceivable to leverage other information structures to perform BFS without using explicit wires.

An alternative way to implement BFS without wires is to utilize two clusters or records: one for the hub at the current level being investigated, and one for the next level hub to be investigated. Initially, the current level list contains the source center.

Calculation starts by highlighting the current level list and going to each hub. For each hub passed through, its adjacent hubs are inspected. If an adjacent hub is not visited, it is marked as visited and added to the other level list. The handle will continue until all hubs in the current level list have been passed.

Once the current level list is fully traversed, the calculation continues to another level list and re-hashes the method to the hub and inspects the next level list. This preparation continues until there are no more unvisited nodes.

usage instructions

Breadth-first method

Breadth-first method

The BFS algorithm starts at the source hub, investigates its neighbors, and most recently moved to neighbors at another level. Use the line information structure to keep track of the hubs you visit. In each cycle, the computation visits a hub, marks it as completed, and queues unvisited adjacent hubs. This preparation will continue until all accessible centers have been visited.

The code initializes a vector adj to represent the infectious list of the chart. Each file of vectors is compared to a center, and each recorded value contains adjacent centers. A BFS traversal is performed by a BFS job, which takes the source hub, the number of hubs N, the vector vis passing through the hub, a separate dp, and the vector v used to keep track of the hubs to be visited. The bfsTraversal job initializes the vanished hub and deletes the vectors, then calls the BFS job to perform the traversal.

algorithm

  • Create an infection list representation of the graph.

  • Initialize a line to store the hub to be accessed.

  • Initialize the disappearing cluster to track disappearing nodes.

  • Initialize the delete cluster to store on each hub what was deleted from the source hub. Set the source hub's delimiter to 0.

  • Enqueue the source hub and check if it has been accessed.

  • Although the pipeline cannot be purged, please do the following:

  • Delete the hub at the head of the queue. For each neighbor hub that has been dequeued and not yet traversed, do the following: Queue the neighbor hub. Mark adjacent hubs as visited. Updated neighbor hub deletion to dequeue hub deletion (also 1).

  • Repeat step 6 until the row is empty.

  • After the BFS traversal is complete, a separate cluster will contain the intervals from the source node to all other centers in the graph.

  • (Optional) You can also keep track of each hub's parent hub in a BFS traversal to get from the source hub to all other hubs in the simplest way.

Example

#include <iostream>
#include <queue>
#include <unordered_set>
using namespace std;

void bfsTraversal(int adjacencyList[][2], int numVertices, int source) {
   bool visited[numVertices + 1] = {false};
   int distances[numVertices + 1] = {0};

   queue<int> vertices;
   vertices.push(source);
   visited[source] = true;

   while (!vertices.empty()) {
      int node = vertices.front();
      cout << node << ", ";
      vertices.pop();

      for (int i = 0; i < 2; i++) {
         int next = adjacencyList[node][i];
            
         if (!visited[next]) {
            vertices.push(next);
            distances[next] = distances[node] + 1;
            visited[next] = true;
         }
      }
   }
}

int main() {
    int adjacencyList[][2] = {{0, 0}, {1, 2}, {3, 4}, {0, 0}, {0, 0}};
    int numVertices = 4;
    int source = 2;

    bfsTraversal(adjacencyList, numVertices, source);

    return 0;
}

Output

2,3,4,0

Example

#include <iostream>
#include <vector>
using namespace std;

void bfsTraversal(vector<vector<int>>& adjacencyList, int N, int source) {
    vector<bool> visited(N + 1, false);
    vector<int> distances(N + 1, 0);
    vector<int> vertices;

    vertices.push_back(source);
    visited[source] = true;

    int curr = 0;
    while (curr < vertices.size()) {
        int node = vertices[curr];
        cout << node << ", ";

        for (int i = 0; i < adjacencyList[node].size(); i++) {
            int next = adjacencyList[node][i];

            if (!visited[next]) {
                vertices.push_back(next);
                distances[next] = distances[node] + 1;
                visited[next] = true;
            }
        }

        curr++;
    }

    cout << "\nDistances from source " << source << ":\n";
    for (int i = 1; i <= N; i++) {
        cout << "Node " << i << ": " << distances[i] << endl;
    }
}

int main() {
    int N = 8;
    vector<vector<int>> adjacencyList(N + 1);
    adjacencyList[0] = {1, 2};
    adjacencyList[1] = {2};
    adjacencyList[2] = {0, 3};
    adjacencyList[3] = {3};
    adjacencyList[4] = {5};
    adjacencyList[5] = {6, 7};
    adjacencyList[6] = {};
    adjacencyList[7] = {};
    adjacencyList[8] = {};

    int source = 5;

    bfsTraversal(adjacencyList, N, source);

    return 0;
}

Output

5, 6, 7, 
Distances from source 5:
Node 1: 0
Node 2: 0
Node 3: 0
Node 4: 0
Node 5: 0
Node 6: 1
Node 7: 1
Node 8: 0

in conclusion

This article describes breadth-first search (BFS) calculations that do not use row information structures. BFS calculations are typically used to navigate a chart in a step-by-step fashion starting from a given source center. Typically, a route is used to store hubs to travel to. Regardless, this article examines an alternative approach that utilizes a basic list or clustering to store the next level of hubs.

This selective use completes the breadth-first study of graphs. This article traces the steps of BFS computation, such as initializing infectious records, maintaining go-to and separation clusters, and using circles to emphasize central levels. It also provides C code instructions illustrating BFS traversal without using a single line. The code accurately studies the graph, prints the BFS traversal permutation, and calculates the distance from the source hub to all other nodes. Overall, this article provides a clear explanation and feasible usage of BFS calculations without the use of lines, demonstrating an alternative approach to navigating graphs in a breadth-first manner.

The above is the detailed content of Breadth-first search does not use queues. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete