Professional Documents
Culture Documents
BFS and DFS
BFS and DFS
Traversal means visiting all the nodes of a graph. Depth first traversal or Depth first
Search is a recursive algorithm for searching all the vertices of a graph or tree data
structure. In this article, you will learn with the help of examples the DFS algorithm, DFS
pseudocode and the code of the depth first search algorithm with implementation in
C++, C, Java and Python programs.
DFS algorithm
A standard DFS implementation puts each vertex of the graph into one of two
categories:
1. Visited
2. Not Visited
The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
DFS example
Let's see how the Depth First Search algorithm works with an example. We use an
undirected graph with 5 vertices.
We start from vertex 0, the DFS algorithm starts by putting it in the Visited list and
putting all its adjacent vertices in the stack.
Next, we visit the element at the top of stack i.e. 1 and go to its adjacent nodes. Since 0
has already been visited, we visit 2 instead.
Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the top of the stack
and visit it.
After we visit the last element 3, it doesn't have any unvisited adjacent nodes, so we
have completed the Depth First Traversal of the graph.
1. DFS(G, u)
2. u.visited = true
3. for each v ∈ G.Adj[u]
4. if v.visited == false
5. DFS(G,v)
6.
7. init() {
8. For each u ∈ G
9. u.visited = false
10. For each u ∈ G
11. DFS(G, u)
12. }
DFS code
The code for the Depth First Search Algorithm with an example is shown below. The
code has been simplified so that we can focus on the algorithm rather than other details.
DFS in C
1. #include <stdio.h>
2. #include <stdlib.h>
3.
4. struct node
5. {
6. int vertex;
7. struct node* next;
8. };
9.
10. struct node* createNode(int v);
11.
12. struct Graph
13. {
14. int numVertices;
15. int* visited;
16. struct node** adjLists; // we need int** to store a two dimensional array.
Similary, we need struct node** to store an array of Linked lists
17. };
18.
19. struct Graph* createGraph(int);
20. void addEdge(struct Graph*, int, int);
21. void printGraph(struct Graph*);
22. void DFS(struct Graph*, int);
23.
24.
25. int main()
26. {
27.
28. struct Graph* graph = createGraph(4);
29. addEdge(graph, 0, 1);
30. addEdge(graph, 0, 2);
31. addEdge(graph, 1, 2);
32. addEdge(graph, 2, 3);
33.
34. printGraph(graph);
35.
36. DFS(graph, 2);
37.
38. return 0;
39. }
40.
41. void DFS(struct Graph* graph, int vertex) {
42. struct node* adjList = graph->adjLists[vertex];
43. struct node* temp = adjList;
44.
45. graph->visited[vertex] = 1;
46. printf("Visited %d \n", vertex);
47.
48. while(temp!=NULL) {
49. int connectedVertex = temp->vertex;
50.
51. if(graph->visited[connectedVertex] == 0) {
52. DFS(graph, connectedVertex);
53. }
54. temp = temp->next;
55. }
56. }
57.
58.
59. struct node* createNode(int v)
60. {
61. struct node* newNode = malloc(sizeof(struct node));
62. newNode->vertex = v;
63. newNode->next = NULL;
64. return newNode;
65. }
66.
67. struct Graph* createGraph(int vertices)
68. {
69. struct Graph* graph = malloc(sizeof(struct Graph));
70. graph->numVertices = vertices;
71.
72. graph->adjLists = malloc(vertices * sizeof(struct node*));
73.
74. graph->visited = malloc(vertices * sizeof(int));
75.
76. int i;
77. for (i = 0; i < vertices; i++) {
78. graph->adjLists[i] = NULL;
79. graph->visited[i] = 0;
80. }
81. return graph;
82. }
83.
84. void addEdge(struct Graph* graph, int src, int dest)
85. {
86. // Add edge from src to dest
87. struct node* newNode = createNode(dest);
88. newNode->next = graph->adjLists[src];
89. graph->adjLists[src] = newNode;
90.
91. // Add edge from dest to src
92. newNode = createNode(src);
93. newNode->next = graph->adjLists[dest];
94. graph->adjLists[dest] = newNode;
95. }
96.
97. void printGraph(struct Graph* graph)
98. {
99. int v;
100. for (v = 0; v < graph->numVertices; v++)
101. {
102. struct node* temp = graph->adjLists[v];
103. printf("\n Adjacency list of vertex %d\n ", v);
104. while (temp)
105. {
106. printf("%d -> ", temp->vertex);
107. temp = temp->next;
108. }
109. printf("\n");
110. }
111. }
DFS in Python
1. def dfs(graph, start, visited=None):
2. if visited is None:
3. visited = set()
4. visited.add(start)
5. print(start)
6. for next in graph[start] - visited:
7. dfs(graph, next, visited)
8. return visited
9.
10. graph = {'0': set(['1', '2']),
11. '1': set(['0', '3', '4']),
12. '2': set(['0']),
13. '3': set(['1']),
14. '4': set(['2', '3'])}
15.
16. dfs(graph, '0')
BFS algorithm
A standard DFS implementation puts each vertex of the graph into one of two
categories:
1. Visited
2. Not Visited
The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
1. Start by putting any one of the graph's vertices at the back of a queue.
2. Take the front item of the queue and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the
back of the queue.
4. Keep repeating steps 2 and 3 until the queue is empty.
The graph might have two different disconnected parts so to make sure that 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 use an
undirected graph with 5 vertices.
We start from vertex 0, the BFS algorithm starts by putting it in the Visited list and
putting all its adjacent vertices in the stack.
Next, we visit the element at the front of queue i.e. 1 and go to its adjacent nodes. Since
0 has already been visited, we visit 2 instead.
Vertex 2 has an unvisited adjacent vertex in 4, so we add that to the back of the queue
and visit 3, which is at the front of the queue.
Only 4 remains in the queue since the only adjacent node of 3 i.e. 0 is already visited.
We visit it.
Since the queue is empty, we have completed the Depth First Traversal of the graph.
BFS pseudocode
create a queue Q
while Q is non-empty
BFS code
The code for the Breadth First Search Algorithm with an example is shown below. The
code has been simplified so that we can focus on the algorithm rather than other details.
BFS in C
1. #include <stdio.h>
2. #include <stdlib.h>
3. #define SIZE 40
4.
5. struct queue {
6. int items[SIZE];
7. int front;
8. int rear;
9. };
10.
11. struct queue* createQueue();
12. void enqueue(struct queue* q, int);
13. int dequeue(struct queue* q);
14. void display(struct queue* q);
15. int isEmpty(struct queue* q);
16. void printQueue(struct queue* q);
17.
18. struct node
19. {
20. int vertex;
21. struct node* next;
22. };
23.
24. struct node* createNode(int);
25.
26. struct Graph
27. {
28. int numVertices;
29. struct node** adjLists;
30. int* visited;
31. };
32.
33. struct Graph* createGraph(int vertices);
34. void addEdge(struct Graph* graph, int src, int dest);
35. void printGraph(struct Graph* graph);
36. void bfs(struct Graph* graph, int startVertex);
37.
38. int main()
39. {
40. struct Graph* graph = createGraph(6);
41. addEdge(graph, 0, 1);
42. addEdge(graph, 0, 2);
43. addEdge(graph, 1, 2);
44. addEdge(graph, 1, 4);
45. addEdge(graph, 1, 3);
46. addEdge(graph, 2, 4);
47. addEdge(graph, 3, 4);
48.
49. bfs(graph, 0);
50.
51. return 0;
52. }
53.
54. void bfs(struct Graph* graph, int startVertex) {
55.
56. struct queue* q = createQueue();
57.
58. graph->visited[startVertex] = 1;
59. enqueue(q, startVertex);
60.
61. while(!isEmpty(q)){
62. printQueue(q);
63. int currentVertex = dequeue(q);
64. printf("Visited %d\n", currentVertex);
65.
66. struct node* temp = graph->adjLists[currentVertex];
67.
68. while(temp) {
69. int adjVertex = temp->vertex;
70.
71. if(graph->visited[adjVertex] == 0){
72. graph->visited[adjVertex] = 1;
73. enqueue(q, adjVertex);
74. }
75. temp = temp->next;
76. }
77. }
78. }
79.
80.
81. struct node* createNode(int v)
82. {
83. struct node* newNode = malloc(sizeof(struct node));
84. newNode->vertex = v;
85. newNode->next = NULL;
86. return newNode;
87. }
88.
89.
90. struct Graph* createGraph(int vertices)
91. {
92. struct Graph* graph = malloc(sizeof(struct Graph));
93. graph->numVertices = vertices;
94.
95. graph->adjLists = malloc(vertices * sizeof(struct node*));
96. graph->visited = malloc(vertices * sizeof(int));
97.
98.
99. int i;
100. for (i = 0; i < vertices; i++) {
101. graph->adjLists[i] = NULL;
102. graph->visited[i] = 0;
103. }
104.
105. return graph;
106. }
107.
108. void addEdge(struct Graph* graph, int src, int dest)
109. {
110. // Add edge from src to dest
111. struct node* newNode = createNode(dest);
112. newNode->next = graph->adjLists[src];
113. graph->adjLists[src] = newNode;
114.
115. // Add edge from dest to src
116. newNode = createNode(src);
117. newNode->next = graph->adjLists[dest];
118. graph->adjLists[dest] = newNode;
119. }
120.
121. struct queue* createQueue() {
122. struct queue* q = malloc(sizeof(struct queue));
123. q->front = -1;
124. q->rear = -1;
125. return q;
126. }
127.
128.
129. int isEmpty(struct queue* q) {
130. if(q->rear == -1)
131. return 1;
132. else
133. return 0;
134. }
135.
136. void enqueue(struct queue* q, int value){
137. if(q->rear == SIZE-1)
138. printf("\nQueue is Full!!");
139. else {
140. if(q->front == -1)
141. q->front = 0;
142. q->rear++;
143. q->items[q->rear] = value;
144. }
145. }
146.
147. int dequeue(struct queue* q){
148. int item;
149. if(isEmpty(q)){
150. printf("Queue is empty");
151. item = -1;
152. }
153. else{
154. item = q->items[q->front];
155. q->front++;
156. if(q->front > q->rear){
157. printf("Resetting queue");
158. q->front = q->rear = -1;
159. }
160. }
161. return item;
162. }
163.
164. void printQueue(struct queue *q) {
165. int i = q->front;
166.
167. if(isEmpty(q)) {
168. printf("Queue is empty");
169. } else {
170. printf("\nQueue contains \n");
171. for(i = q->front; i < q->rear + 1; i++) {
172. printf("%d ", q->items[i]);
173. }
174. }
175. }
BFS in Python
1. import collections
2.
3. def bfs(graph, root):
4. visited, queue = set(), collections.deque([root])
5. visited.add(root)
6. while queue:
7. vertex = queue.popleft()
8. for neighbour in graph[vertex]:
9. if neighbour not in visited:
10. visited.add(neighbour)
11. queue.append(neighbour)
12.
13.
14. if __name__ == '__main__':
15. graph = {0: [1, 2], 1: [2], 2: [3], 3: [1,2]}
16. breadth_first_search(graph, 0)