Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #method 1:using iterative approach bfs
- class Solution:
- #Function to return list containing vertices in Topological order.
- def topoSort(self, V, adj):
- v=[False]*V
- q=[]
- def dfs(src):
- v[src]=True
- for node in adj[src]:
- if v[node]==False:
- dfs(node)
- q.append(src)
- # Code here
- for i in range(V):
- if v[i]==False:
- dfs(i)
- return q[::-1]
- #{
- # Driver Code Starts
- # Driver Program
- #method 2 dfs and colors method
- '''
- 0--->unvisited
- 1--->processing
- 2--->processed
- '''
- class Solution:
- def findOrder(self,adj, n):
- def dfs(src):
- if vis[src]==1:return False
- vis[src]=1
- for ver in adj[src]:
- if vis[ver]!=2:#very imp
- if dfs(ver)==False:
- return False
- vis[src]=2
- ans.append(src)
- vis={i:0 for i in adj.keys()}
- for i in adj.keys():
- if vis[i]==0:
- if dfs(i)==False:return []
- return ans[::-1]
- '''
- These are not complete codes. Just edited some boiler plate but logic is correct.
- Question link:
- https://practice.geeksforgeeks.org/problems/alien-dictionary/1#
- '''
- #method 3 using dictionaruy
- '''
- Here also three colors but bit different
- if key is not in vis:unvisited
- if key is in vis and vis[key]==False:processed
- if key is in vis and vis[key]==True:processing
- '''
- class Solution:
- def findOrder(self,adj, n):
- ans=[]
- def dfs(src):
- if src in vis:
- return vis[src]
- vis[src]=True
- for ver in adj[src]:
- if dfs(ver)==True:
- return ''
- vis[src]=False
- ans.append(src)
- vis={}
- for i in adj.keys():
- if i not in vis:
- if dfs(i):return ''
- #print(ans[::-1])
- return ans[::-1]
Add Comment
Please, Sign In to add comment