Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

DFS algorithm

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.

The DFS algorithm works as follows:

1. Start by putting any one of the graph's vertices on top of a stack.


2. Take the top item of the stack 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 top of stack.
4. Keep repeating steps 2 and 3 until the stack is empty.

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.

DFS pseudocode (recursive implementation)


The pseudocode for DFS is shown below. In the init() function, notice that we run the
DFS function on every node. This is because the graph might have two different
disconnected parts so to make sure that we cover every vertex, we can also run the
DFS algorithm on every node.

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. }

Depth First Search in C++


1. #include <iostream>
2. #include <list>
3. using namespace std;
4.
5. class Graph
6. {
7. int numVertices;
8. list *adjLists;
9. bool *visited;
10.
11. public:
12. Graph(int V);
13. void addEdge(int src, int dest);
14. void DFS(int vertex);
15. };
16.
17. Graph::Graph(int vertices)
18. {
19. numVertices = vertices;
20. adjLists = new list[vertices];
21. visited = new bool[vertices];
22. }
23.
24. void Graph::addEdge(int src, int dest)
25. {
26. adjLists[src].push_front(dest);
27. }
28.
29. void Graph::DFS(int vertex)
30. {
31.
32. visited[vertex] = true;
33. list adjList = adjLists[vertex];
34.
35. cout << vertex << " ";
36.
37. list::iterator i;
38. for(i = adjList.begin(); i != adjList.end(); ++i)
39. if(!visited[*i])
40. DFS(*i);
41. }
42.
43. int main()
44. {
45. Graph g(4);
46. g.addEdge(0, 1);
47. g.addEdge(0, 2);
48. g.addEdge(1, 2);
49. g.addEdge(2, 3);
50.
51. g.DFS(2);
52.
53. return 0;
54. }

DFS Java code


1. import java.io.*;
2. import java.util.*;
3.
4.
5. class Graph
6. {
7. private int numVertices;
8. private LinkedList<Integer> adjLists[];
9. private boolean visited[];
10.
11. Graph(int vertices)
12. {
13. numVertices = vertices;
14. adjLists = new LinkedList[vertices];
15. visited = new boolean[vertices];
16.
17. for (int i = 0; i < vertices; i++)
18. adjLists[i] = new LinkedList<Integer>();
19. }
20.
21. void addEdge(int src, int dest)
22. {
23. adjLists[src].add(dest);
24. }
25.
26. void DFS(int vertex)
27. {
28. visited[vertex] = true;
29. System.out.print(vertex + " ");
30.
31. Iterator ite = adjLists[vertex].listIterator();
32. while (ite.hasNext())
33. {
34. int adj = ite.next();
35. if (!visited[adj])
36. DFS(adj);
37. }
38. }
39.
40.
41. public static void main(String args[])
42. {
43. Graph g = new Graph(4);
44.
45. g.addEdge(0, 1);
46. g.addEdge(0, 2);
47. g.addEdge(1, 2);
48. g.addEdge(2, 3);
49.
50. System.out.println("Following is Depth First Traversal");
51.
52. g.DFS(2);
53. }
54. }

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')

Breadth first search


Traversal means visiting all the nodes of a graph. Breadth first traversal or Breadth 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 BFS algorithm, BFS
pseudocode and the code of the breadth first search algorithm with implementation in
C++, C, Java and Python programs.

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.

The algorithm works as follows:

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

mark v as visited and put v into Q

while Q is non-empty

remove the head u of Q


mark and enqueue all (unvisited) neighbours of u

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. }

Breadth First Search 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.
54. visited[adjVertex] = true;
55. queue.push_back(adjVertex);
56. }
57. }
58. }
59. }
60.
61. int main()
62. {
63. Graph g(4);
64. g.addEdge(0, 1);
65. g.addEdge(0, 2);
66. g.addEdge(1, 2);
67. g.addEdge(2, 0);
68. g.addEdge(2, 3);
69. g.addEdge(3, 3);
70.
71. g.BFS(2);
72.
73. return 0;
74. }

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.
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)

You might also like