{"id":11210,"date":"2025-11-24T12:35:37","date_gmt":"2025-11-24T07:05:37","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=11210"},"modified":"2025-11-24T17:14:08","modified_gmt":"2025-11-24T11:44:08","slug":"find-if-path-exists-in-graph","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/find-if-path-exists-in-graph\/","title":{"rendered":"Find if Path Exists in Graph"},"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=\"\" 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=\"\" 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 the edges list into an adjacency list map so you can quickly find all neighbors of any node.<\/li>\n                <li><strong>Initialize BFS, <\/strong>Start a queue with the source node and mark it as visited.<\/li>\n                <li><strong>Traverse Level-by-Level: <\/strong>\n                <ul>\n                    <li>Repeatedly take a node from the queue.\n                        <ul>\n                            <li>If it is the destination, return <strong>true<\/strong>.<\/li>\n                            <li>Otherwise, push all its unvisited neighbors into the queue and mark them visited.<\/li>\n                        <\/ul>\n                    <\/li>\n                <\/ul>\n                <\/li>\n                <li><Strong>If BFS Ends:<\/Strong>\n                <ul>\n                    <li>If the queue becomes empty and destination is never found, return false.<\/li>\n                <\/ul>\n                <\/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);\"> \nGraph 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: queue = [0] visited = {0} Start BFS \u2192 curr = 0 \u2192 neighbors = [1, 2] \u2192 visit 1 \u2192 queue = [1], \n        visited = {0,1} \u2192 visit 2 \u2192 queue = [1,2], \n        visited = {0,1,2} \u2192 curr = 1 \u2192 neighbors = [0] \u2192 0 already \n        visited \u2192 curr = 2 \u2192 neighbors = [0] \u2192 0 already \n        visited No more nodes left in queue. Destination 5 not reached. \n        \n        Final Answer: false <\/pre> <p><strong>Output:<\/strong> <code>false<\/code><\/p> \n\n<\/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    visited.add(source);\n\n    while(q.length) {\n        let curr = q.shift();\n        if(curr === destination){\n            return true;\n        }\n        for(let neighbor of map[curr]) {\n            if(!visited.has(neighbor)) {\n                q.push(neighbor);\n                visited.add(neighbor);\n            }\n        }\n    }\n    return false;\n\n};\n     <\/code><\/pre>\n        <\/div>\n\n        <!-- Python -->\n        <div class=\"wp_blog_code-tab-content\" data-lang=\"py\">\n            <pre><code class=\"language-python\">\nfrom collections import defaultdict, deque\n\ndef validPath(n, edges, source, destination):\n    if source == destination:\n        return True\n\n    graph = defaultdict(list)\n    for a, b in edges:\n        graph[a].append(b)\n        graph[b].append(a)\n\n    visited = [False] * n\n    q = deque([source])\n    visited[source] = True\n\n    while q:\n        cur = q.popleft()\n        if cur == destination:\n            return True\n        for nei in graph[cur]:\n            if not visited[nei]:\n                visited[nei] = True\n                q.append(nei)\n    return False\n\n# Example:\n# print(validPath(6, [[0,1],[0,2],[3,5],[5,4],[4,3]], 0, 5))  # False\n\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\npublic class Solution {\n    public boolean validPath(int n, int[][] edges, int source, int destination) {\n        if (source == destination) return true;\n\n        List<Integer>[] graph = new ArrayList[n];\n        for (int i = 0; i < n; i++) graph[i] = new ArrayList<>();\n\n        for (int[] e : edges) {\n            int a = e[0], b = e[1];\n            graph[a].add(b);\n            graph[b].add(a);\n        }\n\n        boolean[] visited = new boolean[n];\n        Queue<Integer> q = new LinkedList<>();\n        q.add(source);\n        visited[source] = true;\n\n        while (!q.isEmpty()) {\n            int cur = q.poll();\n            if (cur == destination) return true;\n            for (int nei : graph[cur]) {\n                if (!visited[nei]) {\n                    visited[nei] = true;\n                    q.add(nei);\n                }\n            }\n        }\n        return false;\n    }\n\n    \/\/ Example usage:\n    public static void main(String[] args) {\n        Solution s = new Solution();\n        int n = 6;\n        int[][] edges = {{0,1},{0,2},{3,5},{5,4},{4,3}};\n        System.out.println(s.validPath(n, edges, 0, 5)); \/\/ false\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; \n#include &lt;queue&gt;              \nusing namespace std;\n\nbool validPath(int n, vector<vector<int>>& edges, int source, int destination) {\n    if (source == destination) return true;\n\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\n    vector<char> visited(n, 0);\n    queue<int> q;\n    q.push(source);\n    visited[source] = 1;\n\n    while (!q.empty()) {\n        int cur = q.front(); q.pop();\n        if (cur == destination) return true;\n        for (int nei : graph[cur]) {\n            if (!visited[nei]) {\n                visited[nei] = 1;\n                q.push(nei);\n            }\n        }\n    }\n    return false;\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;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nint validPath(int n, int **edges, int m, int source, int destination) {\n\n    if (source == destination) \n        return 1;\n\n    \/\/ Step 1: Count degree of each node\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]++;\n        deg[b]++;\n    }\n\n    \/\/ Step 2: Allocate adjacency list\n    int **adj = (int **)malloc(n * sizeof(int *));\n    for (int i = 0; i < n; ++i) {\n        if (deg[i] > 0)\n            adj[i] = (int *)malloc(deg[i] * sizeof(int));\n        else\n            adj[i] = NULL;\n    }\n\n    \/\/ Step 3: Fill adjacency list\n    int *idx = (int *)calloc(n, sizeof(int));\n    for (int i = 0; i < m; ++i) {\n        int a = edges[i][0], b = edges[i][1];\n        adj[a][idx[a]++] = b;\n        adj[b][idx[b]++] = a;\n    }\n\n    \/\/ Step 4: BFS setup\n    char *vis = (char *)calloc(n, sizeof(char));\n    int *queue = (int *)malloc(n * sizeof(int));\n    int head = 0, tail = 0;\n\n    queue[tail++] = source;\n    vis[source] = 1;\n\n    \/\/ Step 5: BFS traversal\n    while (head < tail) {\n        int cur = queue[head++];\n\n        if (cur == destination) {\n            \/\/ Free all allocated memory\n            for (int i = 0; i < n; i++)\n                if (adj[i]) free(adj[i]);\n            free(adj);\n            free(deg);\n            free(idx);\n            free(vis);\n            free(queue);\n            return 1;\n        }\n\n        for (int i = 0; i < deg[cur]; ++i) {\n            int nei = adj[cur][i];\n            if (!vis[nei]) {\n                vis[nei] = 1;\n                queue[tail++] = nei;\n            }\n        }\n    }\n\n    \/\/ Cleanup\n    for (int i = 0; i < n; i++)\n        if (adj[i]) free(adj[i]);\n    free(adj);\n    free(deg);\n    free(idx);\n    free(vis);\n    free(queue);\n\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    public bool ValidPath(int n, int[][] edges, int source, int destination) {\n        if (source == destination) return true;\n\n        List<int>[] graph = new List<int>[n];\n        for (int i = 0; i < n; i++) graph[i] = new List<int>();\n\n        foreach (var e in edges) {\n            int a = e[0], b = e[1];\n            graph[a].Add(b);\n            graph[b].Add(a);\n        }\n\n        bool[] visited = new bool[n];\n        Queue<int> q = new Queue<int>();\n        q.Enqueue(source);\n        visited[source] = true;\n\n        while (q.Count > 0) {\n            int cur = q.Dequeue();\n            if (cur == destination) return true;\n            foreach (int nei in graph[cur]) {\n                if (!visited[nei]) {\n                    visited[nei] = true;\n                    q.Enqueue(nei);\n                }\n            }\n        }\n        return false;\n    }\n\n    \/\/ Example usage:\n    public static void Main() {\n        var sol = new Solution();\n        int n = 6;\n        int[][] edges = new int[][] {\n            new int[]{0,1}, new int[]{0,2}, new int[]{3,5}, new int[]{5,4}, new int[]{4,3}\n        };\n        Console.WriteLine(sol.ValidPath(n, edges, 0, 5)); \/\/ False\n    }\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","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,260,176,175,211,811,810,174,172,173],"tags":[],"class_list":["post-11210","post","type-post","status-publish","format-standard","category-algorithms","category-c-c-plus-plus","category-csharp","category-cplusplus","category-data-structures","category-data-structures-and-algorithms","category-dsa","category-java","category-javascript","category-python"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11210","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=11210"}],"version-history":[{"count":2,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11210\/revisions"}],"predecessor-version":[{"id":11212,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/11210\/revisions\/11212"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=11210"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=11210"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=11210"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}