mafulechka
July 16, 2019, 3:03 p.m.

Breadth first search (BFS)

Travel means visiting all nodes of the graph. Breadth first traversal or Breadth first Search is a recursive algorithm for searching all vertices of a graph or tree data structure. In this article, you will see examples of the BFS algorithm, BFS pseudocode, and BFS algorithm code implemented in C++, C, Java, and Python programs.


BFS algorithm

The standard implementation of BFS puts each graph vertex into one of two categories:

  1. Visited.
  2. Not visited.

The purpose of the algorithm is to mark each vertex as visited, avoiding cycles.

The algorithm works like this:

  1. Start by placing any vertex of the graph at the end of the queue.
  2. Take the front element of the queue and add it to the visited list.
  3. Create a list of adjacent nodes of this vertex. Add those not in the visited list to the end of the queue.
  4. Continue repeating steps 2 and 3 until the queue is empty.

A graph can have two different unconnected parts, so to make sure we cover every vertex, we can also run the BFS algorithm on every node.

BFS example

Let's see how the Breadth First Search algorithm works with an example. We are using an undirected graph with 5 vertices.

We start at node 0, the BFS algorithm starts by placing it in the visited list and placing all adjacent nodes on the stack.

We then visit the element at the head of the queue, i.e. 1, and move on to neighboring nodes. Since 0 has already been visited, we visit 2.

Vertex 2 has an unvisited neighbor vertex 4, so we add it to the end of the queue and visit 3, which is at the head of the queue.

Only 4 remains in the queue, since the only neighbor node with 3, i.e. 0, has already been visited. We visit peak 4.

Since the queue is empty, we have completed the breadth traversal of the graph.

BFS pseudo code

  1. create a queue Q
  2. mark v as visited and put v into Q
  3. while Q is non-empty
  4. remove the head u of Q
  5. mark and enqueue all (unvisited) neighbours of u

At BFS

The code for the Breadth First Search algorithm with an example is shown below. The code has been simplified so we can focus on the algorithm and not other details.

BFS in C

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define SIZE 40
  4. struct queue {
  5. int items[SIZE];
  6. int front;
  7. int rear;
  8. };
  9. struct queue* createQueue();
  10. void enqueue(struct queue* q, int);
  11. int dequeue(struct queue* q);
  12. void display(struct queue* q);
  13. int isEmpty(struct queue* q);
  14. void printQueue(struct queue* q);
  15. struct node
  16. {
  17. int vertex;
  18. struct node* next;
  19. };
  20. struct node* createNode(int);
  21. struct Graph
  22. {
  23. int numVertices;
  24. struct node** adjLists;
  25. int* visited;
  26. };
  27. struct Graph* createGraph(int vertices);
  28. void addEdge(struct Graph* graph, int src, int dest);
  29. void printGraph(struct Graph* graph);
  30. void bfs(struct Graph* graph, int startVertex);
  31. int main()
  32. {
  33. struct Graph* graph = createGraph(6);
  34. addEdge(graph, 0, 1);
  35. addEdge(graph, 0, 2);
  36. addEdge(graph, 1, 2);
  37. addEdge(graph, 1, 4);
  38. addEdge(graph, 1, 3);
  39. addEdge(graph, 2, 4);
  40. addEdge(graph, 3, 4);
  41.  
  42. bfs(graph, 0);
  43.  
  44. return 0;
  45. }
  46. void bfs(struct Graph* graph, int startVertex) {
  47. struct queue* q = createQueue();
  48.  
  49. graph->visited[startVertex] = 1;
  50. enqueue(q, startVertex);
  51.  
  52. while(!isEmpty(q)){
  53. printQueue(q);
  54. int currentVertex = dequeue(q);
  55. printf("Visited %d\n", currentVertex);
  56.  
  57. struct node* temp = graph->adjLists[currentVertex];
  58.  
  59. while(temp) {
  60. int adjVertex = temp->vertex;
  61. if(graph->visited[adjVertex] == 0){
  62. graph->visited[adjVertex] = 1;
  63. enqueue(q, adjVertex);
  64. }
  65. temp = temp->next;
  66. }
  67. }
  68. }
  69.  
  70. struct node* createNode(int v)
  71. {
  72. struct node* newNode = malloc(sizeof(struct node));
  73. newNode->vertex = v;
  74. newNode->next = NULL;
  75. return newNode;
  76. }
  77.  
  78. struct Graph* createGraph(int vertices)
  79. {
  80. struct Graph* graph = malloc(sizeof(struct Graph));
  81. graph->numVertices = vertices;
  82.  
  83. graph->adjLists = malloc(vertices * sizeof(struct node*));
  84. graph->visited = malloc(vertices * sizeof(int));
  85.  
  86.  
  87. int i;
  88. for (i = 0; i < vertices; i++) {
  89. graph->adjLists[i] = NULL;
  90. graph->visited[i] = 0;
  91. }
  92.  
  93. return graph;
  94. }
  95.  
  96. void addEdge(struct Graph* graph, int src, int dest)
  97. {
  98. // Add edge from src to dest
  99. struct node* newNode = createNode(dest);
  100. newNode->next = graph->adjLists[src];
  101. graph->adjLists[src] = newNode;
  102.  
  103. // Add edge from dest to src
  104. newNode = createNode(src);
  105. newNode->next = graph->adjLists[dest];
  106. graph->adjLists[dest] = newNode;
  107. }
  108. struct queue* createQueue() {
  109. struct queue* q = malloc(sizeof(struct queue));
  110. q->front = -1;
  111. q->rear = -1;
  112. return q;
  113. }
  114. int isEmpty(struct queue* q) {
  115. if(q->rear == -1)
  116. return 1;
  117. else
  118. return 0;
  119. }
  120. void enqueue(struct queue* q, int value){
  121. if(q->rear == SIZE-1)
  122. printf("\nQueue is Full!!");
  123. else {
  124. if(q->front == -1)
  125. q->front = 0;
  126. q->rear++;
  127. q->items[q->rear] = value;
  128. }
  129. }
  130. int dequeue(struct queue* q){
  131. int item;
  132. if(isEmpty(q)){
  133. printf("Queue is empty");
  134. item = -1;
  135. }
  136. else{
  137. item = q->items[q->front];
  138. q->front++;
  139. if(q->front > q->rear){
  140. printf("Resetting queue");
  141. q->front = q->rear = -1;
  142. }
  143. }
  144. return item;
  145. }
  146. void printQueue(struct queue *q) {
  147. int i = q->front;
  148. if(isEmpty(q)) {
  149. printf("Queue is empty");
  150. } else {
  151. printf("\nQueue contains \n");
  152. for(i = q->front; i < q->rear + 1; i++) {
  153. printf("%d ", q->items[i]);
  154. }
  155. }
  156. }

BFS in C++

  1. #include <iostream>
  2. #include <list>
  3.  
  4. using namespace std;
  5.  
  6. class Graph
  7. {
  8. int numVertices;
  9. list *adjLists;
  10. bool* visited;
  11. public:
  12. Graph(int vertices);
  13. void addEdge(int src, int dest);
  14. void BFS(int startVertex);
  15. };
  16.  
  17. Graph::Graph(int vertices)
  18. {
  19. numVertices = vertices;
  20. adjLists = new list[vertices];
  21. }
  22.  
  23. void Graph::addEdge(int src, int dest)
  24. {
  25. adjLists[src].push_back(dest);
  26. adjLists[dest].push_back(src);
  27. }
  28.  
  29. void Graph::BFS(int startVertex)
  30. {
  31. visited = new bool[numVertices];
  32. for(int i = 0; i < numVertices; i++)
  33. visited[i] = false;
  34.  
  35. list queue;
  36.  
  37. visited[startVertex] = true;
  38. queue.push_back(startVertex);
  39.  
  40. list::iterator i;
  41.  
  42. while(!queue.empty())
  43. {
  44. int currVertex = queue.front();
  45. cout << "Visited " << currVertex << " ";
  46. queue.pop_front();
  47.  
  48. for(i = adjLists[currVertex].begin(); i != adjLists[currVertex].end(); ++i)
  49. {
  50. int adjVertex = *i;
  51. if(!visited[adjVertex])
  52. {
  53. visited[adjVertex] = true;
  54. queue.push_back(adjVertex);
  55. }
  56. }
  57. }
  58. }
  59.  
  60. int main()
  61. {
  62. Graph g(4);
  63. g.addEdge(0, 1);
  64. g.addEdge(0, 2);
  65. g.addEdge(1, 2);
  66. g.addEdge(2, 0);
  67. g.addEdge(2, 3);
  68. g.addEdge(3, 3);
  69. g.BFS(2);
  70.  
  71. return 0;
  72. }

BFS Java code

  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. class Graph
  5. {
  6. private int numVertices;
  7. private LinkedList<Integer> adjLists[];
  8. private boolean visited[];
  9.  
  10. Graph(int v)
  11. {
  12. numVertices = v;
  13. visited = new boolean[numVertices];
  14. adjLists = new LinkedList[numVertices];
  15. for (int i=0; i i = adjLists[currVertex].listIterator();
  16. while (i.hasNext())
  17. {
  18. int adjVertex = i.next();
  19. if (!visited[adjVertex])
  20. {
  21. visited[adjVertex] = true;
  22. queue.add(adjVertex);
  23. }
  24. }
  25. }
  26. }
  27.  
  28. public static void main(String args[])
  29. {
  30. Graph g = new Graph(4);
  31.  
  32. g.addEdge(0, 1);
  33. g.addEdge(0, 2);
  34. g.addEdge(1, 2);
  35. g.addEdge(2, 0);
  36. g.addEdge(2, 3);
  37. g.addEdge(3, 3);
  38.  
  39. System.out.println("Following is Breadth First Traversal "+
  40. "(starting from vertex 2)");
  41.  
  42. g.BFS(2);
  43. }
  44. }

BFS in Python

  1. import collections
  2. def bfs(graph, root):
  3. visited, queue = set(), collections.deque([root])
  4. visited.add(root)
  5. while queue:
  6. vertex = queue.popleft()
  7. for neighbour in graph[vertex]:
  8. if neighbour not in visited:
  9. visited.add(neighbour)
  10. queue.append(neighbour)
  11. if __name__ == '__main__':
  12. graph = {0: [1, 2], 1: [2], 2: [3], 3: [1,2]}
  13. breadth_first_search(graph, 0)

Do you like it? Share on social networks!

s
  • Dec. 6, 2021, 8:51 p.m.
  1. for (int i=0; i i = adjLists[currVertex].listIterator();

это foreach или где?

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html