how to write recursive DFS scientifically

Principles for Writing Correct Recursive Functions in DFS Algorithms
When implementing a Depth-First Search (DFS) algorithm using recursion, it's crucial to structure your recursive function correctly to ensure it works as intended. Here are the key principles to follow:

  1. Start with the Base Case (Exit Condition)
    Purpose: The base case determines when the recursion should stop. It prevents infinite recursion and potential stack overflows.
    Placement: Write the base case at the very beginning of your recursive function.
    Example:
void dfs(Node* node) {
if (node == nullptr) return; // Base case: exit if node is null
// Rest of the code
}
  1. Process the Current Node
    Purpose: Perform the necessary operations on the current node, such as marking it as visited or processing its value.
    Placement: Typically placed immediately after the base case and before the recursive calls.
    Example:
void dfs(Node* node, unordered_set<Node*>& visited) {
if (node == nullptr) return; // Base case
if (visited.count(node)) return; // Avoid revisiting nodes
visited.insert(node); // Mark as visited
// Process the node (e.g., print or store its value)
}
  1. Make Recursive Calls
    Purpose: Explore adjacent nodes or child nodes by making recursive calls.
    Placement: After processing the current node.
    Example:
void dfs(Node* node, unordered_set<Node*>& visited) {
if (node == nullptr || visited.count(node)) return; // Base cases
visited.insert(node); // Process current node
for (Node* neighbor : node->neighbors) {
dfs(neighbor, visited); // Recursive call to neighbors
}
}
  1. Order of Writing
    When writing your recursive function:

Base Case First: Always start by defining your exit conditions.
Process Current Node: Handle the current node's processing needs.
Recursive Calls: Finally, proceed to recursive calls to child or adjacent nodes.
5. Avoid Common Pitfalls
Infinite Recursion: Without a proper base case, your function may call itself indefinitely.
Revisiting Nodes: In graphs or trees with cycles, use a visited data structure to prevent processing the same node multiple times.
Stack Overflows: Deep recursion can lead to stack overflows; consider iterative solutions with explicit stacks if necessary.
6. Example: DFS in a Binary Tree

void dfs(TreeNode* node) {
if (node == nullptr) return; // Base case
// Process current node
cout << node->val << " ";
// Recursive calls
dfs(node->left);
dfs(node->right);
}
  1. Example: DFS in a Graph with Cycle Detection
void dfs(int node, vector<vector<int>>& graph, vector<bool>& visited) {
if (visited[node]) return; // Base case to avoid cycles
visited[node] = true; // Process current node
for (int neighbor : graph[node]) {
dfs(neighbor, graph, visited); // Recursive call
}
}
  1. Summary
    Base Case First: Write your exit conditions at the beginning to ensure the recursion terminates.
    Process Before Recursion: Handle the current node's logic before diving deeper.
    Recursive Calls After: Place recursive calls after processing to continue the traversal.
    Consistency: Maintain a consistent structure to make your code readable and maintainable.
    By following these principles, you'll be able to write correct and efficient recursive functions for DFS algorithms. Remember, starting with the base case not only prevents errors but also clarifies the termination condition of your recursion.
posted @   ijpq  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2021-10-14 python 类的前向声明
2021-10-14 一些数学运算
2021-10-14 CUDA 3D convolution
2021-10-14 3.31面试pony.ai
2021-10-14 CS61C Project1
2021-10-14 C的泛型实现
点击右上角即可分享
微信分享提示