I have encoded a solution for non-recursive DFS, but I cannot change it to do topological sorting:
def dfs(graph,start): path = [] stack = [start] while stack != []: v = stack.pop() if v not in path: path.append(v) for w in reversed(graph[v]): if w not in path and not w in stack: stack.append(w) return path
Any ideas on how to change it?
With the recursive version, I can easily sort:
def dfs_rec(graph,start,path): path = path + [start] for edge in graph[start]: if edge not in path: path = dfs_rec(graph, edge,path) print start return path
Input:
>>> graph = { 1: [2, 3], 2: [4, 5, 6], 3: [4,6], 4: [5,6], 5: [6], 6: [] } >>> dfs_rec(graph,1,[]) 6 5 4 2 3 1 [1, 2, 4, 5, 6, 3] >>> dfs(graph,1) [1, 2, 4, 5, 6, 3] >>> graph = { 1: [3], 3: [5,6], 5: [4], 4: [7], 7: [], 6: [] } >>> print dfs_rec(graph,1,[]) 7 4 5 6 3 1 [1, 3, 5, 4, 7, 6] >>> print dfs(graph,1) [1, 3, 5, 4, 7, 6]
so i need to also get this order in non-recursive.
Non-recursive solution:
I think this could also be a solution, tag me if I'm wrong.
def dfs(graph,start): path = [] stack = [start] label = len(graph) result = {} while stack != []:
Input:
graph = { 1: [3], 3:[5,6] , 5:[4] , 4:[7], 7:[],6:[]} print dfs(graph,1)
Output:
([1, 3, 5, 4, 7, 6], {1: 7, 2: 4, 3: 5, 4: 6, 5: 3, 6: 1}) 1 / 3 /\ 5 6 / 4 / 7