{"id":11213,"date":"2025-11-24T13:12:18","date_gmt":"2025-11-24T07:42:18","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=11213"},"modified":"2025-11-24T17:16:04","modified_gmt":"2025-11-24T11:46:04","slug":"dfs_recursive","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/dfs_recursive\/","title":{"rendered":"DFS Recursive"},"content":{"rendered":"\n<!-- Inorder & Postorder recursive approach: 4 -->\n<link\n    href=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/themes\/prism-tomorrow.min.css\"\n    rel=\"stylesheet\"\n\/>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/prism.min.js\"><\/script>\n<script src=\"https:\/\/cdn.jsdelivr.net\/npm\/prismjs@1.29.0\/plugins\/autoloader\/prism-autoloader.min.js\"><\/script>\n\n<style>\n.wp_blog_theme {\n  --primary: #E58C32;\n  --secondary: #030302;\n  --light-bg: #fef9f4;\n  --text-dark: #2d2d2d;\n  --tab-radius: 12px;\n  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);\n  --code-bg: #001f3f;\n  --code-text: #d4f1ff;\n}\n\n.wp_blog_container {\n  font-family: 'Segoe UI', sans-serif;\n  background: var(--light-bg);\n  margin: 0;\n  padding: 0;\n  color: var(--text-dark);\n}\n\n\/* Heading *\/\n.wp_blog_main-heading {\n  text-align: center;\n  font-size: 2.4rem;\n  color: var(--primary);\n  margin-top: 2.5rem;\n  font-weight: bold;\n}\n\n\/* Explanation Card *\/\n.wp_blog_explanation,\n.wp_blog_code-tabs-container {\n  max-width: 940px;\n  margin: 2rem auto;\n  padding: 2rem;\n  background: white;\n  border-radius: var(--tab-radius);\n  box-shadow: var(--shadow);\n}\n\n\/* Text and Visuals *\/\n.wp_blog_explanation h2 {\n  font-size: 1.4rem;\n  color: var(--primary);\n  margin-bottom: 0.5rem;\n}\n\n.wp_blog_explanation p,\n.wp_blog_explanation li {\n  font-size: 1.05rem;\n  line-height: 1.7;\n  margin: 0.5rem 0;\n}\n\n.wp_blog_explanation code {\n  background: #fef9f4;   \/* light bg instead of dark blue *\/\n  color: #E58C32;        \/* brand orange *\/\n  padding: 3px 6px;\n  border-radius: 4px;\n  font-family: 'Courier New', monospace;\n  font-weight: 600;      \/* optional, makes it pop *\/\n}\n\n.wp_blog_explanation img {\n  max-width: 100%;\n  border-radius: var(--tab-radius);\n  margin-top: 1rem;\n  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);\n}\n\n\/* Tab Buttons *\/\n.wp_blog_code-tabs-header {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 0.5rem;\n  margin-bottom: 1rem;\n}\n\n.wp_blog_code-tab-button {\n  padding: 0.6rem 1.2rem;\n  border: 1px solid var(--primary);\n  background: white;\n  color: var(--primary);\n  border-radius: 50px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: all 0.3s ease;\n}\n\n.wp_blog_code-tab-button:hover {\n  background: var(--secondary);\n}\n\n.wp_blog_code-tab-button.active {\n  background: var(--primary);\n  color: white;\n}\n\n\/* Code Content *\/\n.wp_blog_code-tab-content {\n  display: none;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n}\n\n.wp_blog_code-tab-content.active {\n  display: block;\n}\n\n.wp_blog_code-tab-content pre {\n  margin: 0;\n  padding: 1.5rem;\n  font-size: 1rem;\n  overflow-x: auto;\n  background: var(--code-bg);\n  border-radius: var(--tab-radius);\n  color: var(--code-text);\n}\n\n\/* Dark mode variables *\/\n.wp_blog_theme.dark-mode {\n  --light-bg: #121212;\n  --text-dark: #f5f5f5;\n  --shadow: 0 4px 12px rgba(255, 255, 255, 0.08);\n  --code-bg: #1e1e1e;\n  --code-text: #c5f0ff;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_explanation {\n  background: #1e1e1e;\n}\n\n\/* Dark mode code highlight *\/\n.wp_blog_theme.dark-mode .wp_blog_explanation code {\n  background: #333;\n  color: #ffd27f;\n}\n\n.wp_blog_theme {\n  position: relative; \/* makes it the reference for absolute children *\/\n}\n\n.wp_blog_toggle-btn {\n  position: absolute;\n  top: 1rem;\n  right: 1rem;\n  z-index: 9999;\n  padding: 0.5rem 0.8rem;\n  border-radius: 10%;\n  background: var(--primary);\n  color: white;\n  font-weight: bold;\n  cursor: pointer;\n  border: none;\n  box-shadow: var(--shadow);\n  transition: background 0.3s, transform 0.2s;\n}\n\n.wp_blog_toggle-btn:hover {\n  background: #cc772e;\n}\n\n.wp_blog_theme.dark-mode .wp_blog_code-tabs-container {\n  background: #1e1e1e;\n}\n<\/style>\n\n<div class=\"wp_blog_container wp_blog_theme\"> \n      <button id=\"blogNotesThemeToggle\" class=\"wp_blog_toggle-btn\">\ud83c\udf19<\/button>\n\n    <h1 class=\"wp_blog_main-heading\"><\/h1>\n    <div class=\"wp_blog_explanation\">\n        <h2>Problem Statement<\/h2>\n\n        <p>\n            There is a <strong>bi-directional<\/strong> graph with n vertices, where each vertex is labeled from 0 to n &#8211; 1 (<strong>inclusive<\/strong>). The edges in the graph are represented as a 2D integer array <code>edges<\/code>, where each <code>edges[i] = [u<sub>i<\/sub>, v<sub>i<\/sub>]<\/code> denotes a bi-directional edge between vertex <code>U<sub>i<\/sub><\/code> and vertex <code>v<sub>i<\/sub><\/code>. Every vertex pair is connected by <strong>at most one<\/strong> edge, and no vertex has an edge to itself.\n        <\/p>\n\n        <p>\n            You want to determine if there is a valid path that exists from vertex source to vertex destination.\n        <\/p>\n\n        <p>\n            Given edges and the integers n, source, and destination, return <i><code>true<\/code> if there is a valid path from source to destination, or false otherwise<\/i>.\n        <\/p>\n                <h2>Example 1:<\/h2>\n                <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/11\/Screenshot-2025-11-24-at-11.43.10-AM.png\" alt=\"\">\n                <p><strong>Input:<\/strong> n = 3, edges = [[0,1],[1,2],[2,0]], source = 0, destination = 2<\/p>\n                <p><strong>Output:<\/strong> true<\/p>\n                <p><strong>Explanation:<\/strong> There are two paths from vertex 0 to vertex 2:\n&#8211; 0 \u2192 1 \u2192 2\n&#8211; 0 \u2192 2<\/p>\n                \n\n                <h2>Example 2:<\/h2>\n                <img decoding=\"async\" src=\"https:\/\/namastedev.com\/blog\/wp-content\/uploads\/2025\/11\/Screenshot-2025-11-24-at-11.44.31-AM.png\" alt=\"\">\n                <p><strong>Input:<\/strong> n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5\nOutput: false<\/p>\n                <p><strong>Output:<\/strong> false<\/p>\n                <p><strong>Explanation: There is no path from vertex 0 to vertex 5.<\/strong><\/p>\n                \n                    <h2>Constraints:<\/h2>\n                   <ul>\n                    <li><code>1 <= n <= 2 * 10<sup>5<\/sup><\/code><\/li>\n                    <li><code>0 <= edges.length <= 2 * 10<sup>5<\/sup><\/code><\/li>\n                    <li><code>0 <= u<sub>i<\/sub>, v<sub>i<\/sub> <= n - 1<\/code><\/li>\n                    <li><code>u<sub>i<\/sub> != v<sub>i<\/sub><\/code><\/li>\n                    <li><code>0 <= source, destination <= n - 1<\/code><\/li>\n                    <li>There are no duplicate edges.<\/li>\n                    <li>There are no self edges.<\/li>\n                   <\/ul>\n\n                <h2>Approach<\/h2>\n              <ul>\n                <li><strong>Build the Graph, <\/strong>Convert edges into a graph using a map where each node stores its neighbors.<\/li>\n                <li><strong>Use DFS to explore, <\/strong>Start DFS from source.<\/li>\n                <li><strong>Track visited nodes: <\/strong> Maintain a visited set to avoid revisiting nodes and infinite loops.\n                <ul>\n                    <li><strong>DFS logic<\/strong>\n                        <ul>\n                            <li>If current node is the destination, return <code>true<\/code>.<\/li>\n                            <li>Visit all unvisited neighbors recursively.<\/li>\n                            <li>If any recursive call returns true, propagate it upward.<\/li>\n                        <\/ul>\n                    <\/li>\n                <\/ul>\n                <\/li>\n                <li><Strong>If DFS ends with no match<\/Strong> Return <code>false<\/code>.<\/li>\n            <\/ul>\n\n                <!-- <h2>Time Complexity:<\/h2>\n                <li>\n                  <p><strong>Time Complexity = O(n)<\/strong>\n                  <\/li>\n                <h2>Space Complexity:<\/h2>\n                <li>\n                  <p><strong>Space Complexity = O(n)<\/strong><\/p>\n                <\/li> -->\n<h2>Dry Run<\/h2> \n<div style=\"background: var(--light-bg); border-left: 4px solid var(--primary); padding: 1rem; border-radius: var(--tab-radius); margin: 1rem 0; color: var(--text-dark);\"> \n    <p><strong>Input:<\/strong> <code>n = 6, edges = [[0,1],[0,2],[3,5],[5,4],[4,3]], source = 0, destination = 5<\/code><\/p> \n    <pre style=\"white-space: pre-wrap; background: var(--code-bg); padding: 1rem; border-radius: 8px; overflow-x: auto; color: var(--code-text);\"> \n        Graph Structure (Adjacency List): 0 \u2192 [1, 2] 1 \u2192 [0] 2 \u2192 [0] 3 \u2192 [5, 4] 5 \u2192 [3, 4] 4 \u2192 [5, 3] \n        Initialize: visited = { } Start DFS: dfs(0) \u2022 curr = 0 \u2022 mark visited = {0} \u2022 neighbors = [1, 2] \n        Explore neighbor 1: dfs(1) \u2022 curr = 1 \u2022 mark visited = {0,1} \u2022 neighbors = [0] \u2022 0 already visited \u2192 \n        return false Explore neighbor 2: dfs(2) \u2022 curr = 2 \u2022 mark visited = {0,1,2} \u2022 neighbors = [0] \u2022 0 already visited \u2192 \n        return false All neighbors of 0 explored \u2192 no path found \n        \n        Final Answer: false <\/pre> <p><strong>Output:<\/strong> <code>false<\/code><\/p> <\/div>\n<\/div>\n\n    <div class=\"wp_blog_code-tabs-container\">\n        <div class=\"wp_blog_code-tabs-header\">\n            <button class=\"wp_blog_code-tab-button active\" data-lang=\"js\">JavaScript<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"py\">Python<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"java\">Java<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"cpp\">C++<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"c\">C<\/button>\n            <button class=\"wp_blog_code-tab-button\" data-lang=\"cs\">C#<\/button>\n        <\/div>\n\n        <!-- JavaScript -->\n        <div class=\"wp_blog_code-tab-content active\" data-lang=\"js\">\n            <pre><code class=\"language-javascript\">\nvar validPath = function(n, edges, source, destination) {\n    let map = {};\n    for(let [x, y] of edges) {\n        if(!map[x]) map[x] = [];\n        if(!map[y]) map[y] = [];\n        map[x].push(y);\n        map[y].push(x);\n    }\n    let q = [source];\n    let visited = new Set();\n    let dfs = (curr) => {\n        if(curr === destination){\n            return true;\n        }\n        visited.add(curr);\n        for(let neighbor of map[curr]) {\n            if(!visited.has(neighbor)) {\n                if(dfs(neighbor)){\n                    return true;\n                }\n            }\n        }\n    return false;\n    }\n    return dfs(source);\n};\n     <\/code><\/pre>\n        <\/div>\n\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n            <pre><code class=\"language-python\">\n# Python\nfrom typing import List\n\ndef validPath(n: int, edges: List[List[int]], source: int, destination: int) -> bool:\n    if source == destination:\n        return True\n    graph = [[] for _ in range(n)]\n    for x, y in edges:\n        graph[x].append(y)\n        graph[y].append(x)\n    visited = set()\n    def dfs(curr):\n        if curr == destination:\n            return True\n        visited.add(curr)\n        for nb in graph[curr]:\n            if nb not in visited:\n                if dfs(nb):\n                    return True\n        return False\n    return dfs(source)\n            <\/code><\/pre>\n        <\/div>\n\n        <!-- Java -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"java\">\n            <pre><code class=\"language-java\">\nimport java.util.*;\n\nclass Solution {\n    private boolean dfs(int curr, int dest, List<Integer>[] graph, boolean[] visited) {\n        if (curr == dest) return true;\n        visited[curr] = true;\n        for (int nb : graph[curr]) {\n            if (!visited[nb] && dfs(nb, dest, graph, visited)) return true;\n        }\n        return false;\n    }\n\n    public boolean validPath(int n, int[][] edges, int source, int destination) {\n        if (source == destination) return true;\n        List<Integer>[] graph = new ArrayList[n];\n        for (int i = 0; i < n; ++i) graph[i] = new ArrayList<>();\n        for (int[] e : edges) {\n            graph[e[0]].add(e[1]);\n            graph[e[1]].add(e[0]);\n        }\n        boolean[] visited = new boolean[n];\n        return dfs(source, destination, graph, visited);\n    }\n}\n     <\/code><\/pre>\n        <\/div>\n\n        <!-- C++ -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"cpp\">\n            <pre><code class=\"language-cpp\">\n#include &lt;vector&gt;              \nusing namespace std;\n\nbool dfs(int curr, int destination, vector<vector<int>>& graph, vector<char>& visited) {\n    if (curr == destination) return true;\n    visited[curr] = 1;\n    for (int nb : graph[curr]) {\n        if (!visited[nb] && dfs(nb, destination, graph, visited)) return true;\n    }\n    return false;\n}\n\nbool validPath(int n, vector<vector<int>>& edges, int source, int destination) {\n    if (source == destination) return true;\n    vector<vector<int>> graph(n);\n    for (auto &e : edges) {\n        graph[e[0]].push_back(e[1]);\n        graph[e[1]].push_back(e[0]);\n    }\n    vector<char> visited(n, 0);\n    return dfs(source, destination, graph, visited);\n}\n    <\/code><\/pre>\n        <\/div>\n\n        <!-- C -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"c\">\n            <pre><code class=\"language-c\">\n#include &lt;stdlib.h&gt;\nint validPath(int n, int **edges, int m, int source, int destination) {\n    if (source == destination) return 1;\n\n    \/\/ 1) degree count\n    int *deg = (int*)calloc(n, sizeof(int));\n    for (int i = 0; i < m; ++i) {\n        int a = edges[i][0], b = edges[i][1];\n        deg[a]++; deg[b]++;\n    }\n\n    \/\/ 2) prefix sums -> offsets\n    int *offset = (int*)malloc((n + 1) * sizeof(int));\n    offset[0] = 0;\n    for (int i = 0; i < n; ++i) offset[i+1] = offset[i] + deg[i];\n    int total = offset[n];\n\n    \/\/ 3) adjacency flat array and cursors\n    int *adj = (int*)malloc(total * sizeof(int));\n    int *cursor = (int*)calloc(n, sizeof(int)); \/\/ counts filled per node\n\n    \/\/ fill adjacency\n    for (int i = 0; i < m; ++i) {\n        int a = edges[i][0], b = edges[i][1];\n        adj[offset[a] + cursor[a]] = b; cursor[a]++;\n        adj[offset[b] + cursor[b]] = a; cursor[b]++;\n    }\n\n    \/\/ 4) visited array and recursion using manual stack (to avoid recursion limits we can use stack)\n    char *visited = (char*)calloc(n, sizeof(char));\n    \/\/ use stack for DFS\n    int *stack = (int*)malloc(n * sizeof(int));\n    int top = 0;\n    stack[top++] = source;\n    while (top > 0) {\n        int curr = stack[--top];\n        if (visited[curr]) continue;\n        if (curr == destination) { \/\/ cleanup and return\n            free(deg); free(offset); free(adj); free(cursor); free(visited); free(stack);\n            return 1;\n        }\n        visited[curr] = 1;\n        int start = offset[curr], end = offset[curr+1];\n        for (int i = start; i < end; ++i) {\n            int nb = adj[i];\n            if (!visited[nb]) stack[top++] = nb;\n        }\n    }\n    free(deg); free(offset); free(adj); free(cursor); free(visited); free(stack);\n    return 0;\n}\n            <\/code><\/pre>\n        <\/div>\n\n        <!-- C# -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"cs\">\n            <pre><code class=\"language-csharp\">\nusing System;\nusing System.Collections.Generic;\n\npublic class Solution {\n    private bool Dfs(int curr, int dest, List<int>[] graph, bool[] visited) {\n        if (curr == dest) return true;\n        visited[curr] = true;\n        foreach (int nb in graph[curr]) {\n            if (!visited[nb] && Dfs(nb, dest, graph, visited)) return true;\n        }\n        return false;\n    }\n\n    public bool ValidPath(int n, int[][] edges, int source, int destination) {\n        if (source == destination) return true;\n        List<int>[] graph = new List<int>[n];\n        for (int i = 0; i < n; i++) graph[i] = new List<int>();\n        foreach (var e in edges) {\n            graph[e[0]].Add(e[1]);\n            graph[e[1]].Add(e[0]);\n        }\n        bool[] visited = new bool[n];\n        return Dfs(source, destination, graph, visited);\n    }\n}\n       <\/code><\/pre>\n        <\/div>\n    <\/div>\n<\/div>\n\n\n<script>\ndocument.addEventListener(\"DOMContentLoaded\", () => {\n  const buttons = document.querySelectorAll(\".wp_blog_code-tab-button\");\n  const contents = document.querySelectorAll(\".wp_blog_code-tab-content\");\n\n  buttons.forEach((button) => {\n    button.addEventListener(\"click\", () => {\n      const lang = button.getAttribute(\"data-lang\");\n\n      buttons.forEach((btn) => btn.classList.remove(\"active\"));\n      contents.forEach((content) => content.classList.remove(\"active\"));\n\n      button.classList.add(\"active\");\n      document\n        .querySelector(`.wp_blog_code-tab-content[data-lang=\"${lang}\"]`)\n        .classList.add(\"active\");\n    });\n  });\n\n  const themeToggle = document.getElementById(\"blogNotesThemeToggle\");\n  const themeContainer = document.querySelector(\".wp_blog_theme\");\n\n  themeToggle.addEventListener(\"click\", () => {\n    themeContainer.classList.toggle(\"dark-mode\");\n    themeToggle.textContent =\n      themeContainer.classList.contains(\"dark-mode\") ? \"\u2600\ufe0f\" : \"\ud83c\udf19\";\n  });\n});\n<\/script>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\ud83c\udf19 Problem Statement There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n &#8211; 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex Ui and vertex vi. Every vertex pair<\/p>\n","protected":false},"author":108,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[210,322,260,176,175,211,811,810,174,172,173],"tags":[],"class_list":{"0":"post-11213","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-algorithms","7":"category-algorithms-and-data-structures","8":"category-c-c-plus-plus","9":"category-csharp","10":"category-cplusplus","11":"category-data-structures","12":"category-data-structures-and-algorithms","13":"category-dsa","14":"category-java","15":"category-javascript","16":"category-python"},"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11213","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/108"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=11213"}],"version-history":[{"count":2,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11213\/revisions"}],"predecessor-version":[{"id":11220,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11213\/revisions\/11220"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=11213"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=11213"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=11213"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}