{"id":26345,"date":"2017-10-26T21:10:21","date_gmt":"2017-10-26T15:40:21","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26345"},"modified":"2018-10-31T14:54:18","modified_gmt":"2018-10-31T09:24:18","slug":"python-programming-find-path-two-vertices-directed-graph","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-programming-find-path-two-vertices-directed-graph\/","title":{"rendered":"Find if there is a path between two vertices in a directed graph"},"content":{"rendered":"<p><span style=\"color: #ff6600;\"><strong>Find if there is a path between two vertices in a directed graph<\/strong><\/span><\/p>\n<p>Given a<a href=\"https:\/\/www.wikitechy.com\/technology\/detect-cycle-directed-graph-using-colors\/\" target=\"_blank\" rel=\"noopener\"> Directed Graph<\/a> and two vertices in it, check whether there is a path from the first given vertex to second. <span id=\"more-18750\"><\/span>For example, in the following graph, there is a path from vertex 1 to 3. As another example, there is no path from 3 to 0.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter wp-image-31627 size-full\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/10\/directed-graph.png\" alt=\"directed-graph\" width=\"295\" height=\"171\" \/><\/p>\n<p>We can either use <a href=\"https:\/\/www.wikitechy.com\/technology\/25857-2\/\" target=\"_blank\" rel=\"noopener\">Breadth First Search<\/a> (BFS) or <a href=\"https:\/\/www.wikitechy.com\/technology\/python-algorithm-depth-first-traversal-dfs-graph\/\" target=\"_blank\" rel=\"noopener\">Depth First Search<\/a> (DFS) to find path between two vertices. Take the first vertex as source in BFS (or DFS), follow the standard BFS (or DFS). If we see the second <a href=\"https:\/\/www.wikitechy.com\/technology\/java-program-vertex-cover-problem-introduction-approximate-algorithm\/\" target=\"_blank\" rel=\"noopener\">vertex<\/a> in our traversal, then return true. Else return false.<\/p>\n<p>Following is <a href=\"https:\/\/www.wikitechy.com\/technology\/26824-2\/\" target=\"_blank\" rel=\"noopener\">Python code<\/a> that use BFS for finding reachability of second vertex from first vertex.<\/p>\n<h4 id=\"python-programming-find-if-there-is-a-path-between-two-vertices-in-a-directed-graph\"><span style=\"color: #993300;\">Python\u00a0Programming\u00a0<strong>Find if there is a path between two vertices in a directed graph:<\/strong><\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># program to check if there is exist a path between two vertices<br\/># of a graph<br\/> <br\/>from collections import defaultdict<br\/>  <br\/>#This class represents a directed graph using adjacency list representation<br\/>class Graph:<br\/>  <br\/>    def __init__(self,vertices):<br\/>        self.V= vertices #No. of vertices<br\/>        self.graph = defaultdict(list) # default dictionary to store graph<br\/>  <br\/>    # function to add an edge to graph<br\/>    def addEdge(self,u,v):<br\/>        self.graph[u].append(v)<br\/>     <br\/>    # Use BFS to check path between s and d<br\/>    def isReachable(self, s, d):<br\/>        # Mark all the vertices as not visited<br\/>        visited =[False]*(self.V)<br\/>  <br\/>        # Create a queue for BFS<br\/>        queue=[]<br\/>  <br\/>        # Mark the source node as visited and enqueue it<br\/>        queue.append(s)<br\/>        visited[s] = True<br\/>  <br\/>        while queue:<br\/> <br\/>            #Dequeue a vertex from queue <br\/>            n = queue.pop(0)<br\/>             <br\/>            # If this adjacent node is the destination node,<br\/>            # then return true<br\/>            if n == d:<br\/>                return True<br\/> <br\/>            #  Else, continue to do BFS<br\/>            for i in self.graph[n]:<br\/>                if visited[i] == False:<br\/>                    queue.append(i)<br\/>                    visited[i] = True<br\/>        # If BFS is complete without visited d<br\/>        return False<br\/>  <br\/># Create a graph given in the above diagram<br\/>g = Graph(4)<br\/>g.addEdge(0, 1)<br\/>g.addEdge(0, 2)<br\/>g.addEdge(1, 2)<br\/>g.addEdge(2, 0)<br\/>g.addEdge(2, 3)<br\/>g.addEdge(3, 3)<br\/> <br\/>u =1; v = 3<br\/> <br\/>if g.isReachable(u, v):<br\/>    print(&quot;There is a path from %d to %d&quot; % (u,v))<br\/>else :<br\/>    print(&quot;There is no path from %d to %d&quot; % (u,v))<br\/> <br\/>u = 3; v = 1<br\/>if g.isReachable(u, v) :<br\/>    print(&quot;There is a path from %d to %d&quot; % (u,v))<br\/>else :<br\/>    print(&quot;There is no path from %d to %d&quot; % (u,v))<\/code><\/pre> <\/div>\n<h3 id=\"output\"><span style=\"color: #003300;\"><strong>Output:<\/strong><\/span><\/h3>\n<pre> There is a path from 1 to 3\r\n There is no path from 3 to 1<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Python Programming &#8211; Find if there is a path between two vertices in a directed graph &#8211; check whether there is a path from the first given vertex to second. <\/p>\n","protected":false},"author":1,"featured_media":31290,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,1,78385,73906,4148],"tags":[78421,78420,78419,78424,78423,78428,78417,78427],"class_list":["post-26345","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-algorithm","category-coding","category-connectivity","category-graph-algorithms","category-python","tag-find-all-paths-between-two-nodes-in-a-graph-c","tag-find-all-paths-between-two-nodes-in-a-graph-java","tag-find-all-paths-from-source-to-destination","tag-find-all-paths-from-source-to-destination-java","tag-find-all-paths-in-a-directed-graph","tag-find-all-possible-paths-between-two-points-in-a-matrix","tag-find-all-possible-paths-between-two-vertices-on-a-graph","tag-graph-check-if-path-exists"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26345","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26345"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26345\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/31290"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26345"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26345"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26345"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}