Syntax error Program to check we can visit any city from any city or not in Python

Program to check we can visit any city from any city or not in Python



Suppose we have n cities represented as a number in range [0, n) and we also have a list of one-way roads that connects one city to another. We have to check whether we can reach any city from any city.

So, if the input is like n = 3, roads = [[0, 1],[0, 2],[1,0],[1,2],[2,0],[2,1]], then the output will be True, as You can go 0 to 1 and 1 to 0

To solve this, we will follow these steps−

  • Define a function dfs() . This will take i, visited, g

  • mark i as visited

  • for each j in g[i], do

    • if j is not visited, then

      • dfs(j, visited, g)

  • Define a function travel() . This will take g

  • visited := a new set

  • dfs(0, visited, g)

  • return true when size of visited is same as n

  • From the main method, do the following−

  • graph := an empty map

  • rev_graph := an empty map

  • for each source u, and destination v in roads, do

    • insert v at the end of graph[u]

    • insert u at the end of rev_graph[v]

  • return true when travel(graph) and travel(rev_graph) both are true

Let us see the following implementation to get better understanding −

Example

Live Demo

class Solution:
   def solve(self, n, roads):
      from collections import defaultdict
         graph = defaultdict(list)
         rev_graph = defaultdict(list)
   for u, v in roads:
      graph[u].append(v)
      rev_graph[v].append(u)
      def dfs(i, visited, g):
      visited.add(i)
   for j in g[i]:
      if j not in visited:
         dfs(j, visited,g)
         def travel(g):
         visited = set()
         dfs(0, visited, g)
      return len(visited)==n
   return travel(graph) and travel(rev_graph)
ob = Solution()
n = 3
roads = [[0, 1],[0, 2],[1,0],[1,2],[2,0],[2,1]]
print(ob.solve(n, roads))

Input

3, [[0, 1],[0, 2],[1,0],[1,2],[2,0],[2,1]]

Output

True
Updated on: 2020-10-05T14:25:52+05:30

805 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements