Depth-first Search (DFS) Algorithm With Example
Updated: Nov 30, 2024

What is a Graph Traversal Algorithm?
Graph traversal is a search technique for finding a vertex in a graph. In the search process, graph traversal is also used to determine the order in which it visits the vertices. Without producing loops, a graph traversal finds the edges to be employed in the search process.
There are two methods to traverse a graph data structure:
• Depth-First Search or DFS algorithm
• Breadth-First Search or BFS algorithm
Following your understanding of graph traversal, you will learn about the depth-first search algorithm.
What is DFS?
The Depth First Search algorithm is a recursive algorithm that uses the idea of backtracking. It involves exhaustive searches of all the nodes by going ahead, if possible, else by backtracking.
Here, the word backtrack means that when you are moving forward and there are no more nodes along the current path, you move backward on the same path to find nodes to traverse. All the nodes will be visited on the current path till all the unvisited nodes have been traversed after which the next path will be selected.
This recursive nature of DFS can be implemented using stacks.
The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.
The DFS algorithm works as follows:
• Start by putting any one of the graph's vertices on top of a stack.
• Take the top item of the stack and add it to the visited list.
• Create a list of that vertex's adjacent nodes. Add the ones which are not in the visited
list to the top of the stack.
• Keep repeating steps 2 and 3 until the stack is empty.
Complexities
Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph.
Auxiliary Space: O(V), since an extra visited array of size V is required.
Implementation
#include <iostream>
#include <vector>
using namespace std;
// Function to perform DFS recursively
void DFS(int node, vector<int> adj[], vector<bool>& visited) {
visited[node] = true;
cout << node << " ";
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
DFS(neighbor, adj, visited);
}
}
}
// Function to initialize and start DFS traversal
void startDFS(int startNode, vector<int> adj[], int numNodes) {
vector<bool> visited(numNodes, false);
DFS(startNode, adj, visited);
}
int main() {
// Create adjacency list for the graph
vector<int> adjList[5];
adjList[0] = {1, 2};
adjList[1] = {0, 2, 3};
adjList[2] = {0, 1, 3};
adjList[3] = {1, 2, 4};
adjList[4] = {3};
// Perform DFS traversal starting from node 0
cout << "DFS traversal starting from node 0: ";
startDFS(0, adjList, 5);
cout << endl;
return 0;
}
Output
DFS traversal starting from node 0: 0 1 2 3 4
Explanation
In this example, we define two functions: DFS to actually traverse the graph using depth-first search, and start DFS to initialize the visited array and begin the traversal at a specified start node.
We then use started with a starting node of 0, generate an adjacency list to represent the graph and execute it. The program outputs a DFS traversal beginning at node 0, in this case, 0 1 2 3 4.
Aspect | Advantages | Disadvantages |
Memory Requirement | Requires only linear memory with respect to the search graph, as it only stores a stack of nodes on the path from the root to the current node. | Not guaranteed to provide a solution. |
Time Complexity | Time complexity to depth d and branching factor b is O(bd), as it generates the same set of nodes as breadth-first search but in a different order. DFS is generally limited by time rather than space | The cut-off depth being smaller can result in higher time complexity. |
Efficiency | If a solution is found without exploring much of the path, the time and space requirements are significantly lower. | Determination of the depth is only possible after the search proceeds. |
Memory Usage | Requires less memory since only the nodes on the current path are stored. | |
Search Space Exploration | By chance, DFS may find a solution without examining much of the search space at all. |
Application
• Detecting a graph's cycle: A graph has a cycle if and only if a back edge is visible during
DFS. As a result, you may run DFS on the graph to look for rear edges.
• Finding Strongly Connected Components in a Graph: A directed graph is strongly
connected if each vertex in the graph has a path to every other vertex.
• Solving mazes and other puzzles with only one solution: By only including nodes in the
current path in the visited set, DFS is used to locate all keys to a maze.
• Path Finding: The DFS algorithm can be customized to discover a path between two
specified vertices, a, and b.
Key Difference between BFS and DFS
• BFS finds the shortest path to the destination, whereas DFS goes to the bottom of a
subtree, then backtracks.
• The full form of BFS is Breadth-First Search, while the full form of DFS is Depth-First
Search.
• BFS uses a queue to keep track of the next location to visit. whereas DFS uses a stack to keep track of the next location to visit.
• BFS traverses according to tree level, while DFS traverses according to tree depth.
• BFS is implemented using a FIFO list; on the other hand, DFS is implemented using a
LIFO list.
• In BFS, you can never be trapped in finite loops, whereas in DFS, you can be trapped in
infinite loops.



https://fly88.promo/ giúp tôi định hướng tốt khi chỉ có ít thời gian và muốn kiểm tra nhanh một khu vực. Tôi thường xác định thể thao trước, sau đó chọn bóng đá nếu cần theo dõi sự kiện, thay vì mở nhiều môn cùng lúc. Cách đi từ nhóm lớn đến nội dung cụ thể giúp phạm vi quan sát gọn hơn. Tôi đánh giá bố cục này phù hợp với những phiên ngắn nhưng có mục tiêu rõ. Sau khi quen đường đi, việc quay lại đúng phần đang quan tâm diễn ra nhanh hơn và giảm đáng kể thời gian tìm kiếm trong những lần truy cập sau
Go88en became the subject of my review as I looked at how its interface supports both quick access and broader exploration. I first checked the homepage, main navigation, account controls, and support options to establish the basic structure. I then moved through several entertainment categories, including card games, live casino, slots, fishing, lottery, and sports. Rather than staying within one section, I repeatedly returned to the main menu and selected another category so I could observe how the navigation behaved over time. I looked at whether labels were distinct enough to prevent confusion and whether the same interaction patterns were used across different areas. The most relevant points from my perspective were information architecture, navigation stability, category recognition, and the ability…
https://nohu90.download/ cho tôi một lý do khác để quan sát trải nghiệm giao dịch. Tôi tập trung vào hai thao tác quan trọng là nạp và rút thay vì xem toàn bộ tính năng cùng lúc. Thời gian xử lý khoảng 1–3 phút và hỗ trợ nhiều phương thức gồm chuyển khoản ngân hàng, ví điện tử, QR, USDT cùng thẻ điện thoại. Khi có nhiều lựa chọn, tôi quan tâm đến cách người dùng phân biệt từng phương thức và biết lựa chọn nào phù hợp với mình. Tôi cũng chú ý đến việc thông tin về giao dịch có được trình bày đủ rõ trước khi thực hiện hay không. Với tôi, trải nghiệm thanh toán tốt không đơn…
GG88 được tôi quan sát từ góc độ một người cần tìm nhanh chức năng giữa nhiều lựa chọn trên cùng hệ thống. Tôi kiểm tra menu chính trước rồi mở tài khoản, hướng dẫn và phần hỗ trợ để xem những mục ngoài trò chơi có dễ nhận biết không. Sau đó, tôi thử thể thao, casino và game bài theo từng nhóm. Ở casino, tôi mở Baccarat, Roulette và Poker; với game bài, tôi kiểm tra Tiến Lên và Mậu Binh. Tiếp theo, tôi chuyển sang slot, nổ hũ và bắn cá nhằm xem lượng nội dung có khiến giao diện trở nên dày không. Xổ số và đá gà được tôi mở thêm trước khi quay lại trang…
https://mm88.today/ là nơi tôi kiểm tra riêng khu vực casino trực tiếp để quan sát cách nhiều loại bàn chơi được trình bày trong cùng một không gian. Tôi lần lượt mở Baccarat, Roulette, Sic Bo và một số nội dung live khác, chú ý đến tên bàn, hình ảnh, thông tin kết quả cùng những thành phần xuất hiện bên cạnh màn hình. Nếu hình ảnh chiếm phần lớn giao diện nhưng thông tin nhận diện lại khó tìm, tôi sẽ phải mất thêm thời gian trước khi xác định đúng nội dung đang xem. Tôi tiếp tục chuyển qua nhiều phòng để đối chiếu cách bố trí giữa các giao diện có cấu trúc tương tự. Qua quá trình…